我正在使用这样的 ruby 数组 splat:
array = *1,2,3
Output = [1, 2, 3]
count = 10 #Initializing count
问题:我希望数组一直持续到count = 10
我尝试这个时它不起作用array = *1,..,count
预期输出: [1、2、3、4、5、6、7、8、9、10]
有没有可能通过这种方法取得成功。
我正在使用这样的 ruby 数组 splat:
array = *1,2,3
Output = [1, 2, 3]
count = 10 #Initializing count
问题:我希望数组一直持续到count = 10
我尝试这个时它不起作用array = *1,..,count
预期输出: [1、2、3、4、5、6、7、8、9、10]
有没有可能通过这种方法取得成功。
count = 10
*(1..count) # => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
您可以简单地使用Kernel#Array
:
Array(1..count)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
(1..count)
.to_a,或者仅(1..count)
当您需要 Enumerable 对象而不是明确的 Array 时。
你必须这样做:
array = [*1..count]
count = 10
count.times.map(&:next)
#=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]