views:

905

answers:

4

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 rails.

Thanks

+1  A: 

lambda is exceptionally useful in named_scope

so that you can pass params to named_scopes

ErsatzRyan
+5  A: 

http://august.lilleaas.net/blog/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.

August Lilleaas
Note: this link is unfortunately broken now.
sscirrus
Thanks for the heads up, fixed.
August Lilleaas
+5  A: 

I don't see where you make the distinction between rails and ruby. If you're writing a rails app, you're writing ruby code, so if it's useful in ruby, it should be useful in rails.

Anyways, 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/

ehsanul
Good point. Some kind of cheat sheet that listed all built-in methods taking lambda could sort of make sense, but if you understand what a lambda is, you don't need such a cheat sheet.
August Lilleaas
A: 

It is a piece of code that allows you to pass around.

It is especially useful in named_scope, it allows to you do something like this:

named_scope :scoped_by_user, lambda {|user| {:conditions=>{:user_id=>user.id}}}

Say you have a Project model and you want to get all the projects for one particular user, you can do something like this:

Project.scoped_by_user(123)
ez