vanoushka vanoushka - 6 months ago 22
Ruby Question

Callback after every `each` iteration when `next` is called

I want to run some code after every iteration of

each
. Is there a way to do this without repeating the code? I tried this:

(1..10).each do |n|
continue = Proc.new {
puts "ended #{n}"
next
}
continue.call if n == 2
puts n
continue.call
end


but it didn't work.

In my actual code, I have lots of
next
calls. That's why it's unpractical to call a method every time I call
next
.

Answer

As I understand the question, you don't want anything executed after continue.call if n==2. If that's correct, you could use the control expression next with an argument.

def m(n)
  puts "Only #{n} more days!"
end

(1..6).each do |n|
  next m(n) if n==3
  puts n
  m(n)
end
1
Only 1 more days!
2
Only 2 more days!
Only 3 more days!
4
Only 4 more days!
5
Only 5 more days!
6
Only 6 more days!
Comments