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 106 def array(depth = 0) 107 nest(depth) { [] } 108 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 89 def identity(depth = 0) 90 nest(depth) { |key| key } 91 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) 53 if depth.zero? 54 if default 55 if block_given? 56 new { |hash, key| hash[key] = yield(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 if block_given? 66 new { |hash, key| hash[key] = nest(depth - 1, &::Proc.new) } 67 else 68 new { |hash, key| hash[key] = nest(depth - 1) } 69 end 70 else 71 new { |hash, key| hash[key] = nest(depth - 1, value) } 72 end 73 end 74 end