From: Todd Benson Date: 2008-11-18T19:40:46+09:00 Subject: Re: function to select only certain key/value pairs from hash? On Mon, Nov 17, 2008 at 11:04 PM, Todd Benson wrote: > 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} I'm not apologizing for the missing result[key] on the lhs, though I know it's pretty important to many to have working code in a message. Anyone with a half a brain knows what I meant, but just to be clean... h = Hash[:a, 1, :b, 2] p [:missing_key].inject({}) {|result, key| result[key] = h[key]; result} => {:missing_key => nil} In any case, reducing a hash (being selective) I think is best done using a reject with a negative in the block (as per Chris Shea's second example). Todd