Declaring an integer Range with step != 1 in Ruby

Posted by Dan Tao on Stack Overflow See other posts from Stack Overflow or by Dan Tao
Published on 2010-06-12T19:06:10Z Indexed on 2010/06/12 19:12 UTC
Read the original article Hit count: 167

Filed under:
|
|
|
|

Hey guys, I'm completely new to Ruby, so be gentle.

Say I want to iterate over the range of even numbers from 2 to 100; how would I do that?

Obviously I could do:

(2..100).each do |x|
    if x % 2 == 0
        # my code
    end
end

But, obviously (again), that would be pretty stupid.

I know I could do something like:

i = 2
while i <= 100
    # my code
    i += 2
end

I believe I could also write my own custom class that provides its own each method (?). I am almost sure that would be overkill, though.

I'm interested in two things:

  1. Is it possible to do this with some variation of the standard Range syntax (i.e., (x..y).each)?
  2. Either way, what would be the most idiomatic "Ruby way" of accomplishing this (using a Range or otherwise)? Like I said, I'm new to the language; so any guidance you can offer on how to do things in a more typical Ruby style would be much appreciated.

© Stack Overflow or respective owner

Related posts about ruby

Related posts about beginner