Lambda's vs Procs


#1

In the Batman Vs Ironman, Lambdas vs. Procs exercise, I do not understand why the Lambda doesn’t print both phrases if it returns control to the method. I understand that the Proc stops processing and doesn’t return, but with the code below I would expect it to say -

Batman will win!
Batman will win!
Iron man will win!

Can you help me undersrtand why the Lambda doesn’t get printed as well?


def batman_ironman_proc
  victor = Proc.new { return "Batman will win!" }
  victor.call
  "Iron Man will win!"
end

puts batman_ironman_proc

def batman_ironman_lambda
  victor = lambda { return "Batman will win!" }
  victor.call
  "Iron Man will win!"
end

puts batman_ironman_lambda


#2
def batman_ironman_proc
  victor = Proc.new { return "Batman will win!" }
  victor.call
  "Iron Man will win!"
end

In the above, the return is immediate so the last line is not encountered. The return value will be the string in the return statement of the Proc.

def batman_ironman_lambda
  victor = lambda { return "Batman will win!" }
  victor.call
  "Iron Man will win!"
end

In the above, the call to the lambda takes place but its return value is ignored since the method returns the last line, hence that line prints.


#3

Ok, I think I see. So with every method with a lambda, can I can expect only the last line to be returned?
meaning that in the code below, it would print “It’s a tie!” since it’s the last line?

def batman_ironman_lambda
  victor = lambda { return "Batman will win!" }
  victor.call
  "Iron Man will win!"
  "It's a tie!"
end

#4

Correct. Ruby implicitly returns the last line of a method.


#5

Ok got it. Thank you for your help!


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.