Open a ruby console (using irb
or rails console
) in a terminal and type return 10
. It should give you the following error:
2.6.9 :020 > return 10
Traceback (most recent call last):
2: from (irb):20
1: from (irb):20:in `rescue in irb_binding'
LocalJumpError (unexpected return)
This is cause there's no enclosing method. To use return
you must be returning from something.
When you use return
in a Proc it is essentially like calling return
from the most upstream context.
So if you execute your example in the console
[1,2].each { |e| return e }
it essentially doing the same thing as typing
return 1
return 2
in the console.
Your other examples don't actually execute what's in the nested proc / lambda which is why there is no error.
But if you call the proc it will throw the same error
[1,2].each { |e| Proc.new { return e }.call } # => LocalJumpError (unexpected return)
The lambda returns in the local context so there's no error
[1,2].each { |e| lambda { return e }.call } # => [1, 2]
This answer has some more examples on using return
within a proc or lambda