From: Robert Klemme Date: 2005-02-14T02:35:02+09:00 Subject: Re: "Joining" strings which may be nil (or) Handling Option hashes "Gavri Fernandez" schrieb im Newsbeitrag news:e3ecfac705021309023584319f@mail.gmail.com... > On Mon, 14 Feb 2005 01:44:57 +0900, Robert Klemme > wrote: >> >> "Gavri Fernandez" schrieb im Newsbeitrag >> news:e3ecfac705021308253ae8704e@mail.gmail.com... > >> 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" > > > This is the solution I hit upon right after I sent my mail. Please > critique while I try to understand your solutions :) > > def get_query(options) > query_fragments = [] > options.each do |key, value| > query_fragments.push("#{key.id2name}:#{value}") > end > query = query_fragments.join(" and ") > end I'm missing the condition. As far as I understood you you want to be able to skip nil values. Did I get this wrong? Apart from that it does certainly what you want. If you want to spare the intermediate array you can do a bit optimization: def get_query(options) q = nil options.each do |k,v| q = (q ? q << " and " : "") << k << ":" << v end q end This is basically a verbose variant of my inject version. > Thanks Robert You're welcome! Kind regards robert