From: Robert Dober Date: 2009-08-14T00:40:01+09:00 Subject: Re: Simple If On Thu, Aug 13, 2009 at 5:00 PM, Robert Klemme wrote: > 2009/8/13 Robert Dober : >> On Thu, Aug 13, 2009 at 10:18 AM, Anthony Eden wrote: >>> On Wed, Aug 12, 2009 at 10:14 PM, Pete Moran wrote: >>>> UPDATE: >>>> >>>> This works >>>> >>>>    if params[:country][:id] >>>>      id = params[:country][:id] >>>>    else >>>>      id = params[:id] >>>>    end >>>> >>>> But is there a oneliner equivalent? >>> >>> id = params[:country][:id] || params[:id] >> maybe safer but still not safe >> >> id = params[:country] && params[:country][:id] || params[:id] > > I'd go for > > id = (params[:country] || params)[:id] that is nicely refactored > > But, this does not seem to be what OP needs.  The Perl code was > > my $id = (exists $hash->{id}) ? $hash->{id} : $_; > > For me that translates to something like this: > > def any_method(some_id_argument) >  id = @hash[:id] || some_id_argument not really, rather id = @hash.fetch( :id, some_id_argument) or the fancier id = @hash.fetch( :id ){ some_id_argument } just for completeness ;) of the API. (This is interesting for some use cases as e.g. throwing an exception in the block, thus begin @hash.fetch( :id ) rescue KeyNotFoundIBelieve raise OMGWhatDidYouDo end becomes @hash.fetch( :id ){ raise OMGWhatDidYouDo, "AGAIN" } ;) HTH Robert >  ... > end > > Kind regards > > robert > > -- > remember.guy do |as, often| as.you_can - without end > http://blog.rubybestpractices.com/ > > -- module Kernel alias_method :λ, :lambda end