arrow_backward Back to blog

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.

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:

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

arrow_backBack

New Project Request