From: "Einar Magnús Boson" Date: 2008-11-18T14:23:50+09:00 Subject: Re: function to select only certain key/value pairs from hash? On 18.11.2008, at 05:00 , 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} > > If that's what you want, great. > > Todd > if that is a problem it's easy to fix hash = {:a => 1, :b => 2, :c => 3, :d => 4, :str => "test"} find = [:a, :d, :str, :extra] selected = find.inject({}) { |result, key| val=hash[key] result[key]=val if val result } p selected # >> {:str=>"test", :a=>1, :d=>4} given: f, h = find.size, hash.size This method is O(f) because hash lookup is O(1) The other way it's O(f*h). so if the hash is big it should make a difference. If the elements always are just a few it doesn't really matter. einarmagnus