From: Todd Benson Date: 2008-11-18T14:00:32+09:00 Subject: Re: function to select only certain key/value pairs from hash? On Mon, Nov 17, 2008 at 7:44 PM, Einar Magnús Boson wrote: > This is what I meant to do, a lot more efficient to look up the values > you're lookin for than looping through all keys for every element. > > hash = {:a => 1, > :b => 2, > :c => 3, > :d => 4, > :str => "test"} > > selected = [:a, :d, :str].inject({}){|result, key| result[key]= > hash[key];result} > > > p selected > > # >> {:str=>"test", :a=>1, :d=>4} You will get nils for none existing keys that way. selected = [:whatever].inject({}){|result, key| = hash[key]; result} #=> {:whatever => nil} If that's what you want, great. Todd