When should a lambda or proc be used? I have seen them described as anonymous functions, but I am struggling to understand this concept. I would appreciate any links to or examples of when you might use one in Ruby, but especially in Ruby on Rails.
Lambda functions are used when you need a function for a short period of time. This is commonly used when you want to pass a function as an argument to higher-order functions, that is, functions that take other functions as their arguments.
Ruby lambda 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.
There are only two main differences. First, a lambda checks the number of arguments passed to it, while a proc does not. This means that a lambda will throw an error if you pass it the wrong number of arguments, whereas a proc will ignore unexpected arguments and assign nil to any that are missing.
http://augustl.com/blog/2008/procs_blocks_and_anonymous_functions/ has a run-down of what blocks/procs/lambdas are, how you can use them, and how they compare to functions in other languages. It definitely answers your question.
Do be aware that the last section 'A note on lambdas' mentions a point that is only true in Ruby 1.8 and changed in 1.9 - Ruby: Proc.new { 'waffles' } vs. proc { 'waffles' }
I don't see where you make the distinction between Ruby on Rails and Ruby. If you're writing a Ruby on Rails application, you're writing Ruby code, so if it's useful in Ruby, it should be useful in Ruby on Rails.
Anyway, this article, Some Useful Closures in Ruby, should be helpful, as well as this: http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/
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