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



283
284
285
286
287
288
# File 'lib/gemmy/patches/hash_patch.rb', line 283

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



289
290
291
# File 'lib/gemmy/patches/hash_patch.rb', line 289

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