From: Brian Candler Date: 2008-11-18T19:03:22+09:00 Subject: Re: function to select only certain key/value pairs from has Aryk Grosz wrote: > I want to do something like this > > hash.from_keys(:a,:b) => {:a=> 1, :b=> 2} In ruby1.9, Hash#select returns another Hash. But you'd still be iterating the 'wrong way' (that is, iterating through the hash and doing a linear search through the keys) Personally I'd go with: class Hash def from_keys(*keys) keys.inject({}) { |h,k| h[k] = self[k] if has_key?(k); h } end end hash = {:a => 1, :b => 2, :c => 3} p hash.from_keys(:a, :b) With ruby19 you can do: keys.each_with_object({}) { |k,h| h[k] = self[k] if has_key?(k) } which is more keystrokes but maybe the teeniest bit more efficient. But I hate each_with_object on the principle that its arguments are the opposite way round to inject :-( -- Posted via http://www.ruby-forum.com/.