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:

ยทยทยท

--
Posted via http://www.ruby-forum.com/.

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: class Range - RDoc Documentation

Good luck!

Mike Edgar
http://carboni.ca/

ยทยทยท

On Feb 3, 2011, at 12:41 AM, Thescholar Thescholar wrote:

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:

--
Posted via http://www.ruby-forum.com/\.

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

ยทยทยท

On Thu, Feb 3, 2011 at 1:41 PM, Thescholar Thescholar <thescholar@hotmail.ca> wrote:

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

Thank you very much!

Your advices were very useful.

ยทยทยท

--
Posted via http://www.ruby-forum.com/.

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

ยทยทยท

On Thu, Feb 3, 2011 at 6:58 AM, botp <botpena@gmail.com> wrote:

On Thu, Feb 3, 2011 at 1:41 PM, Thescholar Thescholar > <thescholar@hotmail.ca> 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 }

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