From: "Einar Magnús Boson" Date: 2008-11-18T10:37:21+09:00 Subject: Re: function to select only certain key/value pairs from hash? On 18.11.2008, at 01:34 , Einar Magnús Boson wrote: > > On 17.11.2008, at 23:46 , Chris Shea wrote: > >> On Nov 17, 3:50 pm, Aryk Grosz wrote: >>> Whenever Im coding I usually come across having to create a new hash >>> from the key/value pairs of another hash. >>> >>> For example, >>> >>> hash = {:a => 1, :b => 2, :c => 3} >>> >>> I want to do something like this >>> >>> hash.from_keys(:a,:b) => {:a=> 1, :b=> 2} >>> >>> Is there something like this already? Perhaps in the facets >>> library? I >>> looked and couldn't find anything. >>> >>> If anybody thinks that I shouldnt even be getting into this >>> situation in >>> the first place, please let me know that as well. >>> -- >>> Posted viahttp://www.ruby-forum.com/. >> >> Hmm... I thought there was a built in method for that. Here's one >> way: >> >> hash = {:a => 1, :b => 2, :c => 3} >> Hash[*hash.select {|k,v| [:a,:b].include?(k)}.flatten] #=> >> {:b=>2, :a=>1} >> >> HTH, >> Chris >> > > > That is ridiculously inefficient and weird :) > > hash = {:a => 1, :b => 2, :c => 3} > > selected = [:a, :b].map{|key|{key, hash[key]}} > > p selected > > # >> [{:a=>1}, {:b=>2}] > > > > > Einar Magnús Boson > +354-661 1649 > einarmagnus@tistron.se > einar.boson@gmail.com > > and now I see that I was stupd. heh. nevermind <.< Einar Magnús Boson +354-661 1649 einarmagnus@tistron.se einar.boson@gmail.com