For Loop with Steps?

  • Thread starter Thescholar Thescholar
  • Start date
T

Thescholar Thescholar

Hello I'm new here :)

And I already have a noob question.

I am wondering how it's possible to iterate through a for loop statement
by 5 rather than by 1.

Let's suppose I want to count from 0..100.

Rather than doing this:
1,2,3,4,5,6,7,8,9,10....97, 98, 99, 100

I would like to count by 5 like this:
0, 5, 10, 15, 20, 25, 30... 90, 95, 100

Anyone knoew how I could achieve this?

Thank you very much in advance!
And nice to meet you :)
 
M

Michael Edgar

Hi there,

If you're on Ruby 1.8.7 or Ruby 1.9+, you can use the Range class's =
"step" method
with either a for loop, or with blocks:

for x in (0..100).step(5)
puts x
end

or

(0..100).step(5) do |x|
puts x
end

You can equivalently do 0.step(100, 5) in place of (0..100).step(5) =96 =
they're equivalent.

If you're on an older version of Ruby, you may only be able to use the =
second version there -
I don't have an older copy ready to check that though.

Not many rubyists use the for loop these days because it has a couple =
quirks, but
they probably won't trip up a beginner.

To find out more, check out the Range class: =
http://ruby-doc.org/core/classes/Range.html

Good luck!

Mike Edgar
http://carboni.ca/
 
B

botp

I am wondering how it's possible to iterate through a for loop statement
by 5 rather than by 1.

try this,

for i in (0..100).step(5)
p i
end


then compare this,

(0..100).step(5){|i| p i }


best regards -botp
 
R

Robert Klemme

try this,

=A0for i in (0..100).step(5)
=A0 =A0p i
=A0end


then compare this,

=A0(0..100).step(5){|i| p i }

There is also Fixnum#step

irb(main):003:0> 0.step(100, 5) {|i| p i}
0
5
10
15
20
25
30
35
40
45
50
55
60
65
70
75
80
85
90
95
100
=3D> 0
irb(main):004:0>

Cheers

robert


--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,139
Messages
2,570,807
Members
47,356
Latest member
Tommyhotly

Latest Threads

Top