2

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?

3
  • 3
    "What's the reason for this?" - because these are different things with different behaviour. That's one of the differences between them. Commented Apr 5, 2017 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. Commented Apr 5, 2017 at 17:27
  • I see no lambda in the code. Commented Apr 6, 2017 at 12:29

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

4 Comments

Logical answer.
The linked answer is 12 years old and already was 9 years old at the moment on this answer. Things have changed meanwhile.
But lambda and Proc return behavior hasn't changed.
@PeterH.Boling correct

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.