11 Dec, 2007

Published at 03:41AM

Tagged with extensions, programming, ruby, and tips

This post has 4 comments

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.

Comments

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 use has_key? a good bit. I definitely like extract more than pairs, though.

Eric Tuesday, 11 Dec, 2007 Posted at 06:52PM

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

Hash#slice documentation

Ryan Tuesday, 11 Dec, 2007 Posted at 09:03PM

Hmm… somehow I missed that. Thanks.

Do you have something to say about this post?
Retype the image to the right Spam Hint: Are You Human? Textile Formatting Tips

or

Ryan Heath | Site Management A Ruby on Rails production.

This site is a Formed Function. Formed Function LLC | @formedfunction | Get in Touch