Back to Blog

Get in Touch

Bending Ruby (Part I) - An User-friendly Hash using method_missing

By Pradeep Elankumaran August 7, 2007 in rails, ruby, hacks, method_missing, hash

Missing

There’s been a lot of talk about method_missing lately. Let’s do a little example that leverages this freaky but neat little method in our quest to bend Rails to our will. The following code is a handy trick that lets you access key values in a Hash as regular class methods.

class Hash
  def method_missing(method, *params)
    method = method.to_sym
    return self[method] if self.keys.collect(&:to_sym).include?(method)
    super
  end
end

If you have a key called :name, then my_hash[:name] and my_hash.name will now give the same result. If you call some key that doesn’t exist, then the super call tells Object to throw a generic NoMethodError. Neat, no?

P.S. the collect(&:to_sym) shortcut used above actually evaluates to collect{|x| x.to_sym} in Rails. This functionality is not available in Ruby, but it can easily be replicated by overriding the Symbol class, like so:

class Symbol
  def to_proc(*args)
    Proc.new { |*args| args.shift.__send__(self, *args) }
  end
end

Bending Ruby will be a series of posts that will build on one another.

Medium

Pradeep Elankumaran

A former computational scientist, Pradeep was writing sophisticated astrophysical simulations in Ruby well before the language became fashionable. Since then, he has been working with and thinking a lot about social networks, machine learning and applying mathematical models to social data. At Intridea, he's responsible for researching and developing emerging web technologies, launching new products and writing beautiful code. He's also a member of the XMPP Standards Foundation.

More posts by Pradeep Elankumaran

Pradeep Elankumaran

Pradeep Elankumaran

Pradeep Elankumaran

Here's why, in no particular order, we think the

About Us

Intridea is based in Washington, D.C. Most of us live in the DC-MD-VA metro area, though we also have team members in California, Colorado, Kansas, Maine, Minnesota, Missouri, New Hampshire, New York, Pennsylvania, Wisconsin and Wyoming.

Interested in working with us, or have a question?
Feel free to contact us anytime.

© 2013 Intridea, Inc. All Rights Reserved.

Contact Us

DC Office
1020 16th Street NW
7th Floor
Washington, DC 20036
Phone
1-888-968-IDEA (4332)
1-888-968-IDEA (4332)
Email
info@intridea.com
Fax
1-202-280-1472
Twitter
@intridea

Contact Us

DC Office
1020 16th Street NW
7th Floor
Washington, DC 20036
Phone
1-888-968-IDEA (4332)
1-888-968-IDEA (4332)
Get in Touch
Email
info@intridea.com
Fax
1-202-280-1472
Twitter
@intridea

© 2013 Intridea, Inc. All Rights Reserved.

We're Hiring! Directions to office