我有一个范围,如(1000..0)
,我正在使用each
,但它什么也没做。我试图将它转换为一个数组,并得到一个空的数组。如何将降压范围转换为数组?
我也试过(1000..0).step(-1).each
,它告诉我step cant be negative
...
有没有办法使用(1000..0).each
所以它会做重复,或转换成类似[1000,999,998,...,0]
数组?
我有一个范围,如(1000..0)
,我正在使用each
,但它什么也没做。我试图将它转换为一个数组,并得到一个空的数组。如何将降压范围转换为数组?
我也试过(1000..0).step(-1).each
,它告诉我step cant be negative
...
有没有办法使用(1000..0).each
所以它会做重复,或转换成类似[1000,999,998,...,0]
数组?
1000.downto(0).each { |i| ... }
两种方式你可能会去这样做:
(0..1000).each do |i|
n = 1000 - i
# Use n for all calculations
end
(0..1000).to_a.reverse.each do |n|
# Involves creating temporary array, but overhead is usually minor for
# relatively small numbers.
end
不要忘记,你也可以做到这一点没有一个范围:
1001.times do |i|
n = 1000 - i
end
#1000 item array
step_down_array = 1000.step(0, -1).to_a
#small enumerator:
step_down = 1000.step(0, -1)
的http://计算器.com/questions/2070574/is-there-a-reason-that-we-can-iterate-on-reverse-range-in-ruby =>很多工作在这里 – 2013-02-11 18:10:31