数组中的 1 到 100 个奇数 [英] 1 to 100 odd numbers in array
本文介绍了数组中的 1 到 100 个奇数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Ruby 中有什么很酷的方法可以创建一个只有奇数条目(1、3 等)的 1 到 100 数组.我现在有一个循环,但这显然不是一个很酷的方法!有什么建议吗?
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?
我当前的代码:
def create_1_to_100_odd_array
array = [1]
i = 3
while i < 100
array.push i
i += 2
end
array
end
提前致谢
推荐答案
Range 类为此提供了一个非常酷的功能:
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]
这篇关于数组中的 1 到 100 个奇数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文