Module: Nuggets::Hash::NestMixin
- Included in:
- Hash
- Defined in:
- lib/nuggets/hash/nest_mixin.rb
Instance Method Summary collapse
-
#array(depth = 0) ⇒ Object
call-seq: Hash.array() => aHash.
-
#identity(depth = 0) ⇒ Object
call-seq: Hash.identity() => aHash.
-
#nest(depth = 0, value = default = true) ⇒ Object
call-seq: Hash.nest() => aHash Hash.nest([depth[, value]]) => aHash Hash.nest() { |key| … } => aHash.
Instance Method Details
#array(depth = 0) ⇒ Object
106 107 108 |
# File 'lib/nuggets/hash/nest_mixin.rb', line 106 def array(depth = 0) nest(depth) { [] } end |
#identity(depth = 0) ⇒ Object
89 90 91 |
# File 'lib/nuggets/hash/nest_mixin.rb', line 89 def identity(depth = 0) nest(depth) { |key| key } end |
#nest(depth = 0, value = default = true) ⇒ Object
call-seq:
Hash.nest([depth]) => aHash
Hash.nest([depth[, value]]) => aHash
Hash.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}}}}
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/nuggets/hash/nest_mixin.rb', line 52 def nest(depth = 0, value = default = true) if depth.zero? if default if block_given? new { |hash, key| hash[key] = yield(key) } else new { |hash, key| hash[key] = hash.default } end else new { |hash, key| hash[key] = value } end else if default if block_given? new { |hash, key| hash[key] = nest(depth - 1, &::Proc.new) } else new { |hash, key| hash[key] = nest(depth - 1) } end else new { |hash, key| hash[key] = nest(depth - 1, value) } end end end |