When to use a lambda in Ruby on Rails?

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.


Solution 1:

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' }

Solution 2:

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/

Solution 3:

What is lambda?

Try this with your irb.

lam = lambda { puts "Hello world"}
lam.class

#output is
=> Proc

lambda in ruby is also a instance of Proc class. lambdas are a different flavor of procs.

What is Proc?

Proc objects are blocks of code that have been bound to a set of local variables.

proc = Proc.new { puts "Hello World" }
proc.call

#output is
=> Hello World

What is the difference between a proc and lambda? Comparission will explain usecases

Lambdas check the number of arguments, while procs do not.

multiply = lambda { |x,y| x*y }
multiply.call(2,3)  #=>6
multiply.call(2)    #ArgumentError: wrong number of arguments (1 for 2)

multiply = Proc.new {|x| x*x}
multiply.call(2)    # =>4
multiply.call(2,3)  # =>4 (It ignore the second argument)

Lambdas and procs treat the ‘return’ keyword differently (Read the article below for example)

Read this great article for more details http://awaxman11.github.io/blog/2013/08/05/what-is-the-difference-between-a-block/