Module: Gemmy::Patches::HashPatch::InstanceMethods::Autovivified

Defined in:
lib/gemmy/patches/hash_patch.rb

Overview

Turns a hash into one that’s “autovivified” meaning it’s default values for keys is an empty hash. The result is that you can set nested keys without initializing more than one hash layer.

Usage:

hash = {}.autovivified
hash[:a][:b] = 0
puts hash[:a][:b]
=> 0

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

._autovivified(caller_hash) ⇒ Object



271
272
273
274
275
276
# File 'lib/gemmy/patches/hash_patch.rb', line 271

def self._autovivified(caller_hash)
  result = Hash.new do |hash,key|
    hash[key] = Hash.new(&hash.default_proc)
  end
  result.deep_merge caller_hash
end

Instance Method Details

#autovivifiedObject



277
278
279
# File 'lib/gemmy/patches/hash_patch.rb', line 277

def autovivified
  Gemmy::Patches::HashPatch::InstanceMethods::Autovivified._autovivified(self)
end