I'm wondering if it's possible to use a Proc
for skipping iteration in Ruby?
I wrote some piece of code
def validation i
pr = Proc.new do |i|
if i < 3
next
end
end
pr.call(i)
end
(1..5).each do |i|
validation i
puts "#{i} is bigger than 3"
end
and I expected something like this as result:
3 is bigger than 3
4 is bigger than 3
5 is bigger than 3
but instead I got:
1 is bigger than 3
2 is bigger than 3
3 is bigger than 3
4 is bigger than 3
5 is bigger than 3
So is it possible to use somehow next
in Proc
for skipping from outer iteration or there is some other way?
You can't call next
in your validation
method because the loop is external. What you can do is use next
within your (1..5).each
loop that's dependent on a call to validation
. The following code produces your desired result.
Edit - The code has been refactored to make appropriate use of Proc
.
pr = Proc.new {|i| i < 3}
(1..5).each do |i|
next if pr.call(i)
puts "#{i} is bigger than 3"
end