14

我可以这样迭代

(0..10).step(2){|v| puts v}

但是,由于反向范围等于空范围,我不能以这种方式迭代

(10..0).step(2){|v| puts v}

它不会为我带来任何收益。当然,我可以像这样向后迭代

10.downto(0){|v| puts v}

但是downto方法不允许我设置除默认1之外的其他步骤。这是非常基本的东西,所以我想应该有一个内置的方法来做到这一点,我不知道。

4

3 回答 3

23

你为什么不使用Numeric#step

从文档:

Invokes block with the sequence of numbers starting at num, incremented by step (default 1) on each call. The loop finishes when the value to be passed to the block is greater than limit (if step is positive) or less than limit (if step is negative). If all the arguments are integers, the loop operates using an integer counter. If any of the arguments are floating point numbers, all are converted to floats, and the loop is executed floor(n + n*epsilon)+ 1 times, where n = (limit - num)/step. Otherwise, the loop starts at num, uses either the < or > operator to compare the counter against limit, and increments itself using the + operator.

irb(main):001:0> 10.step(0, -2) { |i| puts i }
10
8
6
4
2
0
于 2013-03-30T08:32:38.507 回答
4

step通过跳过不需要的值很容易模拟。像这样的东西:

10.downto(0).each_with_index do |x, idx|
  next if idx % 3 != 0 # every third element
  puts x
end
# >> 10
# >> 7
# >> 4
# >> 1
于 2013-03-30T06:04:47.660 回答
0
10.step(0, -2) do |v| puts "#{v}" end




10
8
6
4
2
0
于 2018-07-23T18:27:42.627 回答