> LçÉettçËäº "Robert Klemme" <bob.news / gmx.net> > Aihe: Re: "Joining" strings which may be nil (or) Handling Option hashes > > > "Gavri Fernandez" <gavri.fernandez / gmail.com> schrieb im Newsbeitrag > news:e3ecfac705021308253ae8704e / mail.gmail.com... > > Hi everyone, > > I want to create a query based on options passed in through > > an options hash to my method. > > > > The query would look like > > "title:ruby and author:dave and publisher:oreilly" > > or > > "title:ruby and publisher:addison-wesley" > > or > > "author:dave" > > or some other combination based on what options have been set in the hash. > > > > options[:author] |= "" followed by Array#join doesn't help me > > because it would lead to successive 'and's in the query. > > > > What is the Ruby Idiom to achieve what I want? > > Lots of, here are some: > > >> opts = {"title"=>"ruby", "author"=>"dave", "publisher"=>"oreilly", > >> "foo"=>nil} > => {"title"=>"ruby", "author"=>"dave", "foo"=>nil, "publisher"=>"oreilly"} > >> opts.select{|k,v|v} > => [["title", "ruby"], ["author", "dave"], ["publisher", "oreilly"]] > >> opts.select{|k,v|v}.map{|k,v| "#{k}=#{v}"}.join(" and ") > => "title=ruby and author=dave and publisher=oreilly" > > 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" Or, possibly more legibly: hsh.to_a.map!{|i| i.join('=')}.join(' and ') ? > Kind regards > > robert E