Arturas Lapinskas
Arturas Lapinskas

Reputation: 336

How to do something on every n operation in ruby loop?

So, I have a ruby loop, how do I print a message every 50 iteration in it, like this:

loop do
  do something
  break if something happend
  puts "Message at every 50 iteration"
end

Upvotes: 1

Views: 1410

Answers (3)

Shoe
Shoe

Reputation: 76240

Considering your condition to be c I think the cleanest way is to use a while loop (or unless depending on the condition):

while c do
    i = (i) ? i + 1 : 1
    puts "This prints every 50 iterations" if (i % 50 == 0)
end

Upvotes: 0

sawa
sawa

Reputation: 168071

Donald Knuth (perhaps not in Ruby) would use an index that counts down instead of one that counts up. That makes the check easier. It also avoids the problem of integer overflow as sigmavirus24 points out.

i = 50
loop do
  # do something
  break if something happend # (as in original)
  i -= 1
  next unless i.zero?
  i = 50
  puts "Message at every 50 iteration"
end

Upvotes: 4

user229044
user229044

Reputation: 239240

Keep a counting variable, and do something every time it becomes divisible by 50.

i = 0;

loop do
  i += 1

  if i % 50 == 0
    puts "This prints every 50 iterations"
  end
end

Upvotes: 6

Related Questions