From: Todd Benson Date: 2008-11-18T14:44:11+09:00 Subject: Re: function to select only certain key/value pairs from hash? On Mon, Nov 17, 2008 at 11:23 PM, Einar Magnús Boson wrote: > > 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). Good point. The use of #inject, though, may cloud that performance analysis. > so if the hash is big it should make a difference. > > If the elements always are just a few it doesn't really matter. I'm an #inject sort of guy so I like the way you approach this. But, there must be a reason why you don't prefer the negative #reject that seems to work for most people. I might benchmark this, but I think object creation and destruction might outweigh the O(f*h). Todd