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



237
238
239
240
241
242
# File 'lib/gemmy/patches/hash_patch.rb', line 237

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



243
244
245
# File 'lib/gemmy/patches/hash_patch.rb', line 243

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