Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

1 to 100 odd numbers in array

Tags:

ruby

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

like image 431
Johan S Avatar asked Nov 25 '12 10:11

Johan S


2 Answers

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] 
like image 157
Vincent B. Avatar answered Sep 28 '22 07:09

Vincent B.


May not be efficient, but a short piece of code:

(1..100).select(&:odd?)

# => [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
like image 20
sawa Avatar answered Sep 28 '22 07:09

sawa