TIL: Automatic Deep Keys with Ruby Hashes
Generate keys automatically for building deep hashes quickly. Best explained with an example.
Generate keys automatically for building deep hashes quickly. Best explained with an example:
hash = {}
hash[:person][:name][:given] = 'Billy'
# NoMethodError (undefined method `[]=' for nil:NilClass)
Set the default hash value using a bit of proc
magic:
hash = Hash.new { |hash,key| hash[key] = Hash.new(&hash.default_proc) }
hash[:person][:name][:given] = 'Billy'
# {:person=>{:name=>{:given=>"Billy"}}}
Member discussion