From: Jeremy McAnally Date: 2008-05-23T09:35:01+09:00 Subject: Re: lambda, ->, haskell, and so on Even though I see the usefulness, that's just ugly. --Jeremy 2008/5/22 Rados�aw Bu�at : > On Thu, May 22, 2008 at 5:37 PM, Berger, Daniel wrote: >> Could someone show me the use case for lambdas with default arguments? >> Why would we need this in practice? >> >> I also don't understand the use case for blocks with default values. > > It's the same case as default values for regular method (functions). > Lambdas, blocks are like anonymous functions (and closures). > For example in ActiveRecord there is recently added new feature named_scope: > > class Post > named_scope :recent, lambda { |*args| {:conditions => ["released_at >> ?", (args.first || 2.weeks.ago)]} } > end > > usage: > > Post.recent # all posts from latest 2 weeks > Post.recent(3.weeks.ago) # all posts from latest 3 weeks > > As you see there is very ugly trick with *args (because you can't just > pust |time=2.weeks.ago| and for |time| there is warning when you don't > put parameter). > > This example comes from Ryan Bates railscasts > (http://railscasts.com/episodes/108). > In Ruby 1.9 it's easier with -> > > named_scope :recent, ->(time = 2.weeks.ago) { {:conditions => > ["released_at > ?", time]} } > > > -- > Rados�aw Bu�at > > http://radarek.jogger.pl - m�j blog > -- http://jeremymcanally.com/ http://entp.com Read my books: Ruby in Practice (http://manning.com/mcanally/) My free Ruby e-book (http://humblelittlerubybook.com/) Or, my blogs: http://mrneighborly.com http://rubyinpractice.com