From: Gavri Fernandez Date: 2005-02-14T02:02:40+09:00 Subject: Re: "Joining" strings which may be nil (or) Handling Option hashes 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 Thanks Robert -- Gavri --------------------------------------------------- I blog here: http://gavri.blogspot.com