ybakos
ybakos

Reputation: 8630

Why does calling a returning Proc, declared within a method, work?

I've been playing with the Codecademy Ruby course and there's an exercise on lambdas and Procs. I do understand the difference, but I don't quite see why the first code listing here works, while the second does not.

Why does this 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

Upvotes: 4

Views: 178

Answers (1)

megas
megas

Reputation: 21791

It's because of how proc behaves with control flow keywords: return, raise, break, redo, retry and etc.

These keywords will jump from the scope where the proc is defined, otherwise the lambda has its own scope so those keywords will jump from lambda's scope.

In your second example the proc is defined in the scope of main. And as tadman commented below, you can't return from main, only exit available.

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

Upvotes: 3

Related Questions