[英]Ruby Array that counts to a given value
Trying to do something like:试图做类似的事情:
def action(number)
nums = [1...number]
code_here...
end
Do I need to write up a "count" snippet for this to work?我是否需要为此编写一个“计数”片段才能工作? Or is something similar to what I'm trying to do possible?
还是类似于我正在尝试做的事情?
There's another option to use enumerators:还有另一个使用枚举器的选项:
1.upto(10).to_a #=> [1,2,3,4,5,6,7,8,9,10]
There are quite a few useful ones.有很多有用的。 For example, if you only need every other number up to certain number you can use:
例如,如果您只需要直到某个数字的所有其他数字,您可以使用:
0.step(100, 2).to_a #=> [0,2,4,6,8,..., 98,100]
Another option would be to use Array constructor:另一种选择是使用 Array 构造函数:
Array.new(10) { |i| i + 1 } #=> [1,2,3,4,5,6,7,8,9,10]
which is a bit more verbose, but gives you much more freedom:这有点冗长,但给你更多的自由:
Array.new(10) { |i| 2 ** i } #=> [1,2,4,8,16,32,64,256,512]
There are two solutions for this as following:有以下两种解决方案:
If you want to add number in the array than:如果要在数组中添加数字:
nums = [*1..number]
# or
nums = (1..number).to_a
Ignoring last number than:忽略最后一个数字:
nums = [*1...number]
# or
nums = (1...number).to_a
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.