1 to 100 odd numbers in array

匿名 (未验证) 提交于 2019-12-03 02:56:01

问题:

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

回答1:

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]  


回答2:

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] 


回答3:

Just toying...

(0...50).map(&:object_id) #or 1.step(100,2).to_a 


回答4:

Since you need a function, then:

def odd_to(n)     (1..n).step(2).to_a end 


回答5:

Not very effective solution, but quite elegant:

(1..100).select {|a| a%2 != 0} 


回答6:

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] 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!