From: William James Date: 2005-02-15T10:19:54+09:00 Subject: Re: "Joining" strings which may be nil (or) Handling Option hashes William James wrote: > Robert Klemme wrote: > > > > Here's a more efficient variant - using #inject of course :-) > > > > >> opts.inject(nil){|s,(k,v)| v ? (s ? s << " and " : "") << k << "=" > << v : > > >> s} > > => "title=ruby and author=dave and publisher=oreilly" > > > I prefer this: > > opts.to_a.map{|x| x.join('=') if x[1]}.compact.join(' and ') > > ----> "title=ruby and author=dave and publisher=oreilly" Too prolix. Better: opts.map{|x| x.join('=') if x[1]}.compact.join(' and ') Here are the stages through which the data travels: {"title"=>"ruby", "author"=>"dave", "foo"=>nil, "publisher"=>"oreilly"} ["title=ruby", "author=dave", nil, "publisher=oreilly"] ["title=ruby", "author=dave", "publisher=oreilly"] "title=ruby and author=dave and publisher=oreilly"