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.
In Ruby, a lambda is an object similar to a proc. Unlike a proc, a lambda requires a specific number of arguments passed to it, and it return s to its calling method rather than returning immediately. proc_demo = Proc. new { return "Only I print!" }
You can run Ruby code in AWS Lambda. Lambda provides runtimes for Ruby that run your code to process events. Your code runs in an environment that includes the AWS SDK for Ruby, with credentials from an AWS Identity and Access Management (IAM) role that you manage.
When using parameters prefixed with ampersands, passing a block to a method results in a proc in the method's context. Procs behave like blocks, but they can be stored in a variable. Lambdas are procs that behave like methods, meaning they enforce arity and return as methods instead of in their parent scope.
In a method argument list, the & operator takes its operand, converts it to a Proc object if it isn't already (by calling to_proc on it) and passes it to the method as if a block had been used.
Lambdas:
Proc
s,def
),I recommend checking out this article that explain procs, blocks, and lambdas.
Edit: This link is outdated. For future reference, try this article
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With