Why does the call to the returned Proc declared as part of the method work?

I played with the Codecademy Ruby course and there is an exercise on lambdas and Procs. I understand the difference, but I do not quite understand why the first code works here and the second does not.

Why does it work:

def batman_ironman_proc p = Proc.new { return "Batman will win!" } p.call "Iron Man will win!" end puts batman_ironman_proc # prints "Batman will win!" 

But not this:

 def batman_ironman_proc(p) p.call "Iron Man will win!" end p = Proc.new { return "Batman will win!" } puts batman_ironman_proc(p) # unexpected return 
+4
source share
1 answer

This is due to the way proc behaves with the keywords of the control flow: return , raise , break , redo , retry , etc.

These keywords will skip from the area where proc defined, otherwise lambda has its own scope so that these keywords go from lambda's .

In your second example, proc is defined in the scope of main. And as the tadman comment below, you cannot return from main , only exit .

Your code will work if you switch from proc to lambda .

+3
source

All Articles