Ruby Language Automatically creating a Deep Hash


Example

Hash has a default value for keys that are requested but don't exist (nil):

a = {}
p a[ :b ] # => nil 

When creating a new Hash, one can specify the default:

b = Hash.new 'puppy'
p b[ :b ]            # => 'puppy'

Hash.new also takes a block, which allows you to automatically create nested hashes, such as Perl's autovivification behavior or mkdir -p:

# h is the hash you're creating, and k the key.
#
hash = Hash.new { |h, k| h[k] = Hash.new &h.default_proc }
hash[ :a ][ :b ][ :c ] = 3

p hash # => { a: { b: { c: 3 } } }