next¶
next を使用して、whileループの次の反復を実行しようとすることができます。nextを実行した後、whileの条件がチェックされ、真であれば、本体が実行されます。
a = 1
while a < 5
a += 1
if a == 3
next
end
puts a
end
# The above prints the numbers 2, 4 and 5
nextは、ブロックからの脱出にも使用できます。例えば
def block(&)
yield
end
block do
puts "hello"
next
puts "world"
end
# The above prints "hello"
breakと同様に、nextは引数を取ることもでき、その引数はyieldによって返されます。
def block(&)
puts yield
end
block do
next "hello"
end
# The above prints "hello"