ruby 数组中的 1 到 100 个奇数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13550042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:32:50  来源:igfitidea点击:

1 to 100 odd numbers in array

ruby

提问by Johan S

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?

在 Ruby 中有什么很酷的方法可以创建一个只有奇数条目(1、3 等)的 1 到 100 的数组。我现在有一个循环,但这显然不是一个很酷的方法!有什么建议?

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

提前致谢

回答by Vincent B.

The Rangeclass 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] 

回答by sawa

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]

回答by steenslag

Just toying...

玩玩而已...

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

回答by FUT

Since you need a function, then:

既然你需要一个函数,那么:

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

回答by samuil

Not very effective solution, but quite elegant:

不是很有效的解决方案,但很优雅:

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

回答by pjs

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]