module Nuggets::Hash::NestMixin
Public Instance Methods
array([depth]) → aHash
click to toggle source
Creates a nested hash, depth
levels deep, that yields arrays at the last level.
Example:
hash = Hash.array(2) hash[:foo][:bar][:a] << 1 << 2 hash[:foo][:bar][:b] << 3 << 4 hash #=> {:foo=>{:bar=>{:a=>[1, 2], :b=>[3, 4]}}}
# File lib/nuggets/hash/nest_mixin.rb 102 def array(depth = 0) 103 nest(depth) { [] } 104 end
identity([depth]) → aHash
click to toggle source
Creates a nested hash, depth
levels deep, that yields the keys themselves at the last level.
Example:
hash = Hash.identity(2) hash[:foo][:bar][:a] #=> :a hash[:foo][:bar][:b] #=> :b hash #=> {:foo=>{:bar=>{:a=>:a, :b=>:b}}}
# File lib/nuggets/hash/nest_mixin.rb 85 def identity(depth = 0) 86 nest(depth) { |key| key } 87 end
nest([depth]) → aHash
click to toggle source
nest([depth[, value]]) → aHash
nest([depth]) { |key| ... } → aHash
Creates a nested hash, depth
levels deep. The final hash will receive a default value of value
or, if value
is not given but a block is given, the result of the key yielded to that block, or, otherwise, the hash's original default value, typically nil
.
NOTE: If you set the default value for one of the nested hashes explicitly, all of the effects described here disappear for that hash because that also means that the default proc will be cleared.
Example:
hash = Hash.nest(2) hash[:foo][:bar][:a] = { x: 1, y: 2 } hash[:foo][:bar][:b] = { x: 0, y: 3 } hash #=> {:foo=>{:bar=>{:b=>{:y=>3, :x=>0}, :a=>{:y=>2, :x=>1}}}}
# File lib/nuggets/hash/nest_mixin.rb 52 def nest(depth = 0, value = default = true, &block) 53 if depth.zero? 54 if default 55 if block_given? 56 new { |hash, key| hash[key] = block[key] } 57 else 58 new { |hash, key| hash[key] = hash.default } 59 end 60 else 61 new { |hash, key| hash[key] = value } 62 end 63 else 64 if default 65 new { |hash, key| hash[key] = nest(depth - 1, &block) } 66 else 67 new { |hash, key| hash[key] = nest(depth - 1, value) } 68 end 69 end 70 end