Bending Ruby (Part I) – An User-friendly Hash using method_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 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) { |*args| args.shift.__send__(self, *args) }   end end

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