Ruby - 每第n次迭代

Dam*_*che 4 ruby

如何使用以下内容在ruby中每隔n次打印一次"Hello":

50.times do
  # every nth say hello
end
Run Code Online (Sandbox Code Playgroud)

Yos*_*ssi 10

(0..10).step(2) do |it| 
  puts it
end
Run Code Online (Sandbox Code Playgroud)

输出:

0
2
4
6
8
10
Run Code Online (Sandbox Code Playgroud)


KL-*_*L-7 10

我认为times不会适用于那种情况.但你可以在范围内迭代:

(1..50).each do |i|
  # print hello if number of iteration is multiple of five
  puts 'Hello' if i % 5 == 0
  # do other stuff
end
Run Code Online (Sandbox Code Playgroud)

更新(感谢d11wtq)

事实证明,Integer#times该块也会产生迭代次数:

50.times do |i|
  # print hello if number of iteration is multiple of five
  puts 'Hello' if (i + 1) % 5 == 0
  # do other stuff
end
Run Code Online (Sandbox Code Playgroud)

数值是从零开始的,所以我们在迭代次数上加1(你可以i % 5 == 4改用,但看起来不太明显).

  • `times`也将迭代索引生成块. (2认同)