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
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]
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]
Just toying...
(0...50).map(&:object_id) #or 1.step(100,2).to_a
Since you need a function, then:
def odd_to(n) (1..n).step(2).to_a end
Not very effective solution, but quite elegant:
(1..100).select {|a| a%2 != 0}
You can do it as a one-liner when you instantiate the array:
def create_array_of_odds_to(n) Array.new((n + 1) / 2) {|i| 2 * i + 1} end create_array_of_odds_to 10 # => [1, 3, 5, 7, 9]