post

A couple of additions to Ruby Hash
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.

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
01
11 Dec 2007 10:57 AM

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.

02
11 Dec 2007 05:18 PM

True, the names aren’t the greatest. Concerning has_keys?, I guess I was immediately biased since I use has_key? a good bit. I definitely like extract more than pairs, though.

03
Eric
11 Dec 2007 11:52 PM

It looks like you may be looking for the Hash#slice method in ActiveSupport:

Hash#slice documentation

04
12 Dec 2007 02:03 AM

Hmm… somehow I missed that. Thanks.




Please rewrite the image text in the SPAM field: Spam Protection

Preview

2008 by Ryan Heath | Get In Touch

flickr

DesolateInfinityLooking upDazedBlurred