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
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
lambda is exceptionally useful in named_scope
so that you can pass params to named_scopes
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.
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/
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)