Why does "Iron Man will win" get printed out? Can you step me through how this Lambda works?



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

puts batman_ironman_proc

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

puts batman_ironman_lambda


Study this paragraph from the lesson text...

Second, when a lambda returns, it passes control back to the calling
method; when a proc returns, it does so immediately, without going back
to the calling method.

We see this played out above. The first example never sees the value, "Iron Man will win!" so it is not the return value, but the one in the Proc is. The second example does see and return the "Iron Man will win!" value. The return is implicit. That is, the last expression in a method, immediately preceding end is a return value.


I thought that the proc doesn't see "Iron Man will win!" and the Lambda sees "Iron Man will win!"


Exactly. That's why "Batman will win!" is printed. It is the return value of the method.

When the lambda is run, it returns "Batman will win!" to the calling method, which then returns "Iron Man will win!".


def batman_iron_man_lambda
  victor = lambda { return "Batman will win!" }

puts batman_iron_man_lambda    # Batman will win!

Now the return value of the method is the return value from the lambda.


This is a slightly more general application of lambda:

def batman_lambda
  victor = lambda { return ['lose','win'][rand(1..100)%2] }
  "Batman will #{victor.call}!"

puts batman_lambda    # Batman will win!
puts batman_lambda    # Batman will lose!


How did you get win or lose if it is random? Thanks.


It will be one or the other. I just showed both. The range contains 50 even numbers and 50 odd numbers. Even is a win, odd is a loss.


i tried to explain to the best of my understanding, which i think is right: http://imgur.com/Z7027HQ

Further to this, i think it relates to the next exercise, in that lets say you want to search an array and return some values - if you are using a proc, it would find the first value and exit the method / whereas a lambda will search all the items of the array until the end (i believe).