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"