179

So I'm iterating over a range like so:

(1..100).each do |n|
    # n = 1
    # n = 2
    # n = 3
    # n = 4
    # n = 5
end

But what I'd like to do is iterate by 10's.

So in stead of increasing n by 1, the next n would actually be 10, then 20, 30, etc etc.

2

4 Answers 4

287

See http://ruby-doc.org/core/classes/Range.html#M000695 for the full API.

Basically you use the step() method. For example:

(10..100).step(10) do |n|
    # n = 10
    # n = 20
    # n = 30
    # ...
end
1
  • 14
    This answer led me to what I was looking for... If you have two times, you can do (time1..time2).step(15.minutes) do |time|
    – daybreaker
    Commented Jan 18, 2014 at 20:11
19

You can use Numeric#step.

0.step(30,5) do |num|
  puts "number is #{num}"
end
# >> number is 0
# >> number is 5
# >> number is 10
# >> number is 15
# >> number is 20
# >> number is 25
# >> number is 30
10

Here's another, perhaps more familiar-looking way to do it:

for i in (0..10).step(2) do
    puts i
end
3
  • 14
    Sorry, but the ruby style guide strongly discourages the use for loops. Commented Apr 10, 2015 at 16:58
  • @DarthEgregious why is that?
    – Doug
    Commented Aug 12, 2018 at 21:20
  • 1
    It's an extension of the philosophy that every thing is an object and every action is a method call. So rather than using a built-in for looping with for, you should use the each method. Commented Aug 13, 2018 at 15:13
7
rng.step(n=1) {| obj | block } => rng

Iterates over rng, passing each nth element to the block. If the range contains numbers or strings, natural ordering is used. Otherwise step invokes succ to iterate through range elements. The following code uses class Xs, which is defined in the class-level documentation.

range = Xs.new(1)..Xs.new(10)
range.step(2) {|x| puts x}
range.step(3) {|x| puts x}

produces:

1 x
3 xxx
5 xxxxx
7 xxxxxxx
9 xxxxxxxxx
1 x
4 xxxx
7 xxxxxxx
10 xxxxxxxxxx

Reference: http://ruby-doc.org/core/classes/Range.html

......

Not the answer you're looking for? Browse other questions tagged or ask your own question.