For Loop with Steps?

Hello I’m new here :slight_smile:

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 :slight_smile:

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)
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/

On Thu, Feb 3, 2011 at 1:41 PM, Thescholar Thescholar
[email protected] wrote:

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

Thank you very much!

Your advices were very useful.

On Thu, Feb 3, 2011 at 6:58 AM, botp [email protected] wrote:

then compare this,

(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
=> 0
irb(main):004:0>

Cheers

robert