lambda and proc

396 views

What's the return value of the following Ruby code?

def procs_return
  -> { return :lambda }.call

  proc { return :proc }.call

  return :return
end

procs_return # => ???

The correct answer is

:lambda

:proc

:return

It raises LocalJumpError

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

Explanation

The procs_return method demonstrates the difference in behavior between a lambda and a proc regarding returning from a method.

Here's what happens:

Lambda Execution

-> { return :lambda }.call

Inside the method, a lambda is created using the -> syntax. This lambda returns the symbol :lambda. The lambda is immediately called using .call.

When the lambda encounters the return statement, it only exits the lambda itself, not the entire method.

Therefore, the method continues execution after the lambda call.

Proc Execution

proc { return :lambda }.call

After the lambda, a proc is created using the proc keyword. This proc returns the symbol :proc.

Similar to the lambda, the proc is called immediately using .call.

However, when the proc encounters the return statement, it exits not just the proc but the entire method.

This behavior is because procs handle return differently; they break out of the method they're defined in.

Outcome

  1. Despite encountering the return statement inside the lambda, the method continues execution and reaches the explicit return :return statement.
  2. However, when the proc encounters the return statement, it exits the method immediately, bypassing any subsequent code.
  3. Therefore, the method returns :proc, indicating that the proc's return statement interrupted the method execution.

Conclusion

In summary, the critical difference lies in how lambdas and procs handle return statements.

Lambdas return only from themselves, while procs can break out of the method they're defined in, affecting the method's flow.

This distinction is essential to understand when working with Ruby's functional programming features.

Voilà!

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

RubyCademy ©