Module: Nuggets::Hash::NestMixin

Included in:
Hash
Defined in:
lib/nuggets/hash/nest_mixin.rb

Instance Method Summary (collapse)

Instance Method Details

- (Object) nest(depth = 0, value = default = true)

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(3)
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}}}}


53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/nuggets/hash/nest_mixin.rb', line 53

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