10

I am reading along in pickaxe 1.9 and the author uses lambda like this:

bo = lambda {|param| puts "You called me with #{param}"}
bo.call 99     => 'You called me with 99'
bo.call "cat"  => 'You called me with cat'

My question is this: How is this any better/worse/different than just defining a method that does that same thing? Like so:

def bo(param)
  puts "You called me with #{param}"
end

bo("hello") => 'You called me with hello'

To me the lambda syntax seems much more confusing and spaghetti-like.

1
  • 1
    Also lambda is a special Proc. It is not a method. Commented Apr 18, 2012 at 20:09

2 Answers 2

17

Lambdas:

  • are variations of Procs,
  • can be converted to/from blocks,
  • do not begin a new closure scope (meaning you can access variables defined outside the scope of your lambda, unlike def),
  • can be passed around as variables.

I recommend checking out this article that explain procs, blocks, and lambdas.

Edit: This link is outdated. For future reference, try this article

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

1 Comment

Great simple answer! This is everything that I am looking for
3

The advantage that defining a lambda gives you is that you can then pass that lambda object as an attribute to another method.

def method1 &b
  #... some code
  b.call
end

def method2 &b
  #... some more code...
  b.call
end

def method3 &b
  b.call
  #even more code here
end

myCallback = lambda { "this is a callback that can be called from several methods"}

You can then use it like this:

method1 &myCallback
method2 &myCallback
method3 &myCallback

And the beauty of this, is that you only wrote of code of the callback once, but used it 3 times....

I would recommend you take a look at this link for further reading :)

1 Comment

in the case of blocks, you can also use yield instead of block.call. This is in fact preferred as it's a good bit faster.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.