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

Posted by on August 7th, 2007.

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.

Share:

1 Response to “Bending Ruby (Part I) - An User-friendly Hash using method_missing”

  1. Vince

    I like the #4 from this post better. http://ola-bini.blogspot.com/2006/09/ruby-metaprogramming-techniques.html


Leave a Reply