Module: Bury

Defined in:
lib/bury.rb,
lib/bury/version.rb

Constant Summary collapse

VERSION =
"2.0.0"

Instance Method Summary collapse

Instance Method Details

#bury(keys, value) ⇒ Hash

Merge Hash according to the array of keys passed to Hash

Examples:

example

hash = {a: {d: 2}}
hash.bury([:a,:b,:c], 1) # => {a:{b:{c:1},d:2}}
hash # => {a: {d: 2}}

Parameters:

  • keys (Array<String|Symbol>)
  • value (Object)

Returns:

  • (Hash)


13
14
15
16
17
18
19
20
21
# File 'lib/bury.rb', line 13

def bury(keys, value)
  merge_proc = lambda do |_key, old_value, new_value|
    [old_value, new_value].all? { |v| v.is_a? Hash } ? old_value.merge(new_value, &merge_proc) : new_value
  end
  create_hash_recursively = lambda do |i = 0|
    { keys[i] => keys.size - 1 == i ? value : create_hash_recursively.call(i + 1) }
  end
  merge(create_hash_recursively.call, &merge_proc)
end

#bury!(keys, value) ⇒ Hash

Destructively merges Hashes according to the array of keys passed to it

Examples:

example

hash = {a: {d: 2}}
hash.bury!([:a,:b,:c], 1) # => {a:{b:{c:1},d:2}}
hash # => {a:{b:{c:1},d:2}}

Parameters:

  • keys (Array<String|Symbol>)
  • value (Object)

Returns:

  • (Hash)


31
32
33
# File 'lib/bury.rb', line 31

def bury!(keys, value)
  replace(bury(keys, value))
end