Programming Kata: Treat a Hash Like a JavaScript Object

In JavaScript, objects look and act an awful lot like hashes:

var hash = {a: 'b', c: 'd'}

hash.a  #=> 'b'
hash['c']  #=> 'd'

How can we mimic this in Ruby? It’s easier than you might think. Ruby classes have an instance method called `method_missing` that is called whenever…you guessed it…it can’t find the method you asked for. Since Ruby allows us to open up any class and extend it, let’s do that now:

class Hash
  def method_missing method_name, *args, &block
    return self[method_name] if has_key?(method_name)
    return self[$1.to_sym] = args[0] if method_name.to_s =~ /^(.*)=$/

Now we have JavaScript object-like power in Ruby hashes:

hash = {:five => 5, :ten => 10}
hash.five  #=> 5
hash.fifteen = 15
hash[:fifteen]  #=> 15

We’re doing three things here. First, we’re checking if the hash has a key by the given method name (as a symbol). If it does, we return the value. Next, if method_name ends in an equal sign, we create a new hash entry with the value specified. Finally, it’s very important to always call `super` at the end of `method_missing`. This way, if the method is still missing, other parents classes up the inheritance chain might provide the solution.

You can practice this as an interactive kata on Codewars.