Ruby - every nth iteration

How to print "Hello" every nth iteration in ruby, using something like:

50.times do # every nth say hello end 
+4
source share
2 answers

I don't think times will work in this case. But instead, you can iterate over the range:

 (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 

Updated (thanks to d11wtq)

It turned out that Integer#times also gives the iteration number to the block:

 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 

The numbering is zero, so we add 1 to the iteration number (you can use i % 5 == 4 instead, but that looks less obvious).

+10
source
 (0..10).step(2) do |it| puts it end 

Outputs:

 0 2 4 6 8 10 
+9
source

Source: https://habr.com/ru/post/1388455/


All Articles