Project

General

Profile

Feature #13179 ยป update_deep_hash.rb

bettisworth (wurde _), 02/01/2017 06:45 PM

 
#!/usr/bin/env ruby
# update_deep_hash.rb
# Author: Andy Bettisworth
# Description: Solve problem of updating deep hash values

def init_key_hash(keys, value)
key_hash = keys.collect { |e| [e, nil] }.to_h
key_hash[keys.last] = value
key_hash
end

def set_key_hash(hash, key_hash)
key_hash.each do |k,v|
if v.nil?
hash = hash.key?(k) ? hash[k] : {}
key_hash[k] = hash
end
end
key_hash
end

def build_new_hash(key_hash, new_hash={})
key_hash.keys.reverse.each do |k|
if key_hash[k].is_a? Hash
new_hash = { k => key_hash[k].merge!(new_hash) }
else
new_hash[k] = key_hash[k]
end
end
new_hash
end

def update_deep_hash(hash, update_key)
value = update_key.pop
key_hash = init_key_hash(update_key, value)
key_hash = set_key_hash(hash, key_hash)
new_hash = build_new_hash(key_hash)
new_hash
end

# h = { a: { b: 2, c: { d: 4, e: 6 } } }
# puts h.inspect
# #=> {:a=>{:b=>2, :c=>{:d=>4, :e=>6}}}
# h = update_deep_hash(h, [:a, :b, 5])
# puts h.inspect
# #=> {:a=>{:b=>5, :c=>{:d=>4, :e=>6}}}

# h = { a: { b: { c: { d: 4, e: 6, f: { g: 8 }}}}}
# puts h.inspect
# #=> {:a=>{:b=>{:c=>{:d=>4, :e=>6, :f=>{:g=>8}}}}}
# h = update_deep_hash(h, [:a, :b, :c, :e, 10])
# puts h.inspect
# #=> {:a=>{:b=>{:c=>{:d=>4, :e=>10, :f=>{:g=>8}}}}}

# h = { a: { b: { c: 6, f: 8 }}}
# puts h.inspect
# #=> {:a=>{:b=>{:c=>6, :f=>8}}}
# h = update_deep_hash(h, [:a, :b, { d: 'foo', f: 'bar' }])
# puts h.inspect
# #=> {:a=>{:b=>{:d=>"foo", :f=>"bar"}}}

# h = { a: { b: { c: 6, f: 8 }}}
# puts h.inspect
# #=> {:a=>{:b=>{:c=>6, :f=>8}}}
# h = update_deep_hash(h, [:a, :b, :d, 'foo'])
# # puts h.inspect
# #=> {:a=>{:b=>{:c=>6, :f=>8, :d=>"foo"}}}

# h = { a: { b: { c: 6, f: 8 }}}
# puts h.inspect
# #=> {:a=>{:b=>{:c=>6, :f=>8}}}
# h = update_deep_hash(h, [:a, :b, :d, :e, :g, 'foo'])
# puts h.inspect
# #=> {:a=>{:b=>{:c=>6, :f=>8, :d=>{:e=>{:g=>"foo"}}}}}

# h = { a: { b: { c: 6, f: 8 }}}
# puts h.inspect
# #=> {:a=>{:b=>{:c=>6, :f=>8}}}
# h = update_deep_hash(h, [:a, :b, d: {e: {g: 'foo'}}])
# puts h.inspect
# #=> {:a=>{:b=>{:d=>{:e=>{:g=>"foo"}}}}}

# h = { a: { b: { c: 6, f: 8 }}}
# puts h.inspect
# #=> {:a=>{:b=>{:c=>6, :f=>8}}}
# h = update_deep_hash(h, [:a, :b, :d, {e: {g: 'foo'}}])
# puts h.inspect
# #=> {:a=>{:b=>{:c=>6, :f=>8, :d=>{:e=>{:g=>"foo"}}}}}
    (1-1/1)