2 ms·
Here's a slightly evil way of handling this specific case in Ruby: d = lambda {|hash,key| Hash.new(&d) } foo = Hash.new(&d) p foo['a']['b']['c'] The
by vidarh 11y ago
Here's a slightly evil way of handling this specific case in Ruby:
d = lambda {|hash,key| Hash.new(&d) }
foo = Hash.new(&d)
p foo['a']['b']['c']
The argument to "Hash.new" is the default value, or a on object that takes the hash object itself and the key, and returns the default value (and optionally stores it in the hash, which makes it great for memoization). In this case, whenever accessing a non-existent hash key, it returns another hash with the same closure as the default...
Of course it's likely to blow up in all kinds of ways since anything trying to do "if foo['a']" to check of 'a' is present in foo will break, for example.