A couple of additions to Ruby Hash
Ruby is near perfect in and of itself, and it’s sometimes hard to fathom how Rails improves upon that perfectness. But there are still times when a little extra is needed. Luckily, that’s not a problem. Here are a couple of methods I’ve added to Hash that I use a good bit.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class Hash # names = { # :first => 'ryan', # :middle => 'paul', # :last => 'heath' # } # # names.has_keys? :first, :last # => true # names.has_keys? :first, :title # => false def has_keys?(*keys) keys.each do |key| return false unless has_key?(key) end return true end # names.pairs :first, :last # => {:first => 'ryan', :last => 'heath'} # names.pairs :middle # => {:middle => 'paul'} def pairs(*keys) keys.inject({}) { |h,k| h[k] = self[k]; h } end end |
They’re simple extensions, but I find them to be quite useful. And I wouldn’t be surprised if Rails (or Ruby for that matter) already have something similar, but I couldn’t find them if so.

Simon Russell Tuesday, 11 Dec, 2007 Posted at 05:57AM
Nice.
I’m always adding things to Hash. That pairs one is a bit confusingly named I reckon; someone I work with just made a similar one called “extract”. The has_keys? one could probably also be made clearer by calling it has_all_keys or something (though that’s pretty ugly).
You could also overload key? to take an vararg array, or something.
I couldn’t find anything like these either.
Ryan Tuesday, 11 Dec, 2007 Posted at 12:18PM
True, the names aren’t the greatest. Concerning
has_keys?, I guess I was immediately biased since I usehas_key?a good bit. I definitely likeextractmore thanpairs, though.Eric Tuesday, 11 Dec, 2007 Posted at 06:52PM
It looks like you may be looking for the
Hash#slicemethod in ActiveSupport:Hash#slice documentation
Ryan Tuesday, 11 Dec, 2007 Posted at 09:03PM
Hmm… somehow I missed that. Thanks.