1

Why is Proc in ruby return before executing remaining codes in a method from which Proc was called?

def hello
  a = Proc.new{ return }
  a.call
  puts "Hello"
end


def proc
  hello
  puts "Proc"
end

Here return will skip puts "Hello" and prints only puts "Proc"

But lambda prints puts "Hello" as well.

What's the reason for this?

Sreeraj Chundayil
  • 5,548
  • 3
  • 29
  • 68
  • 3
    "What's the reason for this?" - because these are different things with different behaviour. That's one of the differences between them. – Sergio Tulentsev Apr 05 '17 at 17:23
  • 2
    Sometimes you do want to return from the entire thing and not just the block. Contrived and silly example: `def find_even; [1, 2, 3].each {|elem| return elem if elem.even? }; end`. So, if that's the case, use block/proc. if you want the opposite, use lambda. – Sergio Tulentsev Apr 05 '17 at 17:27
  • I see no `lambda` in the code. – Martin Vidner Apr 06 '17 at 12:29

1 Answers1

4

You should see comment in this answer https://stackoverflow.com/a/723/4576274.

It states

A lambda is an anonymous method. Since it's a method, it returns a value, and the method that called it can do with it whatever it wants, including ignoring it and returning a different value.

A Proc is like pasting in a code snippet. It doesn't act like a method. So when a return happens within the Proc, that's just part of the code of the method that called it

Community
  • 1
  • 1
Pramod
  • 1,376
  • 12
  • 21