Early return from blocks in ruby

mudasobwa profile image Aleksei Matiushkin ・1 min read

Ruby 2.5 introduced Object#yield_self that, according to the documentation, “yields self to the block and returns the result of the block.”

Nah, we all have had it since Ruby 0.9:

42.tap do |forty_two|
  break "Yielded: #{forty_two}, returning string"
#⇒ "Yielded: 42, returning string"

Both break and next might be used inside any block, not only inside enumerations/loops. Once stated, it sounds evident. break immediately returns from any λ (block, proc, lambda.) If a parameter is passed, it’s being returned. If not, nil is the default value.

NB break is stack-safe return in any ruby implementation. It effectively returns from the current block, rewinding the stack by exactly one frame.

->() { puts "Hi!"; break 42; puts "Unreachable code" }.()
# "Hi"
#⇒ 42

Also, next might be used to simulate early return from blocks:

42.tap do |ft|
  puts "Hi"
  next unless ft == :foo
  puts "Unreachable code"
# "Hi"
#⇒ 42

Happy coding!

Posted on Dec 25 '18 by:

mudasobwa profile

Aleksei Matiushkin


NB! I am _not_ a member of #DEVCommunity. → I like: Elixir, Erlang, Ruby, R, C, COBOL. → I hate: Apple, JS, Rails, haters. → I am more functional, than object oriented.


markdown guide