Ruby:如何遍历一个范围,但以设置的增量?


1 Answers

您可以使用Numeric#step

0.step(30,5) do |num|
  puts "number is #{num}"
end
# >> number is 0
# >> number is 5
# >> number is 10
# >> number is 15
# >> number is 20
# >> number is 25
# >> number is 30
Question

所以我正在遍历一个范围,如下所示:

(1..100).each do |n|
    # n = 1
    # n = 2
    # n = 3
    # n = 4
    # n = 5
end

但我想要做的是迭代10。

因此,除了将n增加1以外,接下来的n实际上是10,然后是20,30等等。




这是另一种可能更为熟悉的方式:

for i in (0..10).step(2) do
    puts i
end



Related