From: Chris Shea Date: 2008-11-18T08:51:32+09:00 Subject: Re: function to select only certain key/value pairs from hash? On Nov 17, 4:46 pm, 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 Yeah, or the simpler: hash.reject {|k,v| ![:a,:b].include?(k)}