Ruby Block Examples and Their Relationship with Break, Next and Return
Last updated:Here's some examples on the use of some keywords to exit from or otherwise alter the behaviour of ruby blocks.
Note that, although I'm using Array iterators (like
each
), this is in no way restricted to those an can be used with other iterators likewhile
,for
,until
and so on.
Using break
with no parameters
Just breaks out of the block, returns nothing
foo = [1,2,3,4,5].each do |element|
if (element * 2) == 8
break
end
end
puts foo # prints nil
Using break
with a parameter
Yes, you can also use break
with an argument. In that case, it returns that parameter from the block:
foo = [1,2,3,4,5].each do |element|
if (element * 2) == 8
break element
end
end
puts foo # prints 4
Using next
Calling next
causes the iterator to skip to the next iteration directly. The second if
gets skipped and the result is just the array itself (i.e., nothing was returned from the block).
foo = [1,2,3,4,5].each do |element|
if (element * 2) == 8
next
end
if element * 2 == 8
break element # this is never reached
end
end
puts foo # prints [1, 2, 3, 4, 5]
Using return
This causes the method this block lives in to return.
def bar
foo = [1,2,3,4,5].each do |element|
if (element * 2) == 8
return element
end
end
puts foo # this is never reached
end
puts bar # prints 4
- P.S.: Examples run on ruby version 2.1