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.
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.






Comments
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.
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.It looks like you may be looking for the
Hash#slicemethod in ActiveSupport:Hash#slice documentation
Hmm… somehow I missed that. Thanks.