Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 242
Cameron Avatar asked Aug 05 '09 12:08

Cameron


People also ask

When should lambdas be used?

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.

What is lambda in Ruby on Rails?

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.

What is the difference between a proc and a lambda?

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.


2 Answers

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

like image 112
August Lilleaas Avatar answered Sep 28 '22 02:09

August Lilleaas


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/

like image 28
ehsanul Avatar answered Sep 28 '22 04:09

ehsanul