JS-flavored hashes in Ruby

I’ve become frustrated with Ruby’s syntax for hashes.

1
2
3
4
hash = {:foo => 'bar'} # not a fan
=> {:foo=>"bar"}
hash[:foo]
=> "bar"

Here’s a (non-recommended) way to make it look better by extending the Hash class directly:

1
2
3
4
5
6
7
class Hash
def method_missing(m)
k = m.to_sym
return self[k] if self.has_key? k
super
end
end

This allows the following syntax:

1
2
3
4
hash = {foo: 'bar'}
=> {:foo=>"bar"}
hash.foo
=> "bar"
dark
sans