Johan S Johan S - 3 months ago 8
Ruby Question

1 to 100 odd numbers in array

Is there any cool way in Ruby to create an array with 1 to 100 with only odd entries (1, 3 etc). I now have a loop for this but that is obviously not a cool way to do it! Any suggestions?

My current code:

def create_1_to_100_odd_array
array = [1]
i = 3
while i < 100
array.push i
i += 2
end

array
end


Thanks in advance

Answer

The Range class comes with a very cool feature for that purpose:

1.9.3-p286 :005 > (1..10).step(2).to_a
 => [1, 3, 5, 7, 9] 
Comments