Project

General

Profile

Feature #13179 ยป update_deep_hash.rb

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

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

    
6
def init_key_hash(keys, value)
7
  key_hash = keys.collect { |e| [e, nil] }.to_h
8
  key_hash[keys.last] = value
9
  key_hash
10
end
11

    
12
def set_key_hash(hash, key_hash)
13
  key_hash.each do |k,v|
14
    if v.nil?
15
      hash = hash.key?(k) ? hash[k] : {}
16
      key_hash[k] = hash
17
    end
18
  end
19
  key_hash
20
end
21

    
22
def build_new_hash(key_hash, new_hash={})
23
  key_hash.keys.reverse.each do |k|
24
    if key_hash[k].is_a? Hash
25
      new_hash = { k => key_hash[k].merge!(new_hash) }
26
    else
27
      new_hash[k] = key_hash[k]
28
    end
29
  end
30
  new_hash
31
end
32

    
33
def update_deep_hash(hash, update_key)
34
  value = update_key.pop
35
  key_hash = init_key_hash(update_key, value)
36
  key_hash = set_key_hash(hash, key_hash)
37
  new_hash = build_new_hash(key_hash)
38
  new_hash
39
end
40

    
41
# h = { a: { b: 2, c: { d: 4, e: 6 } } }
42
# puts h.inspect
43
# #=> {:a=>{:b=>2, :c=>{:d=>4, :e=>6}}}
44
# h = update_deep_hash(h, [:a, :b, 5])
45
# puts h.inspect
46
# #=> {:a=>{:b=>5, :c=>{:d=>4, :e=>6}}}
47

    
48
# h = { a: { b: { c: { d: 4, e: 6, f: { g: 8 }}}}}
49
# puts h.inspect
50
# #=> {:a=>{:b=>{:c=>{:d=>4, :e=>6, :f=>{:g=>8}}}}}
51
# h = update_deep_hash(h, [:a, :b, :c, :e, 10])
52
# puts h.inspect
53
# #=> {:a=>{:b=>{:c=>{:d=>4, :e=>10, :f=>{:g=>8}}}}}
54

    
55
# h = { a: { b: { c: 6, f: 8 }}}
56
# puts h.inspect
57
# #=> {:a=>{:b=>{:c=>6, :f=>8}}}
58
# h = update_deep_hash(h, [:a, :b, { d: 'foo', f: 'bar' }])
59
# puts h.inspect
60
# #=> {:a=>{:b=>{:d=>"foo", :f=>"bar"}}}
61

    
62
# h = { a: { b: { c: 6, f: 8 }}}
63
# puts h.inspect
64
# #=> {:a=>{:b=>{:c=>6, :f=>8}}}
65
# h = update_deep_hash(h, [:a, :b, :d, 'foo'])
66
# # puts h.inspect
67
# #=> {:a=>{:b=>{:c=>6, :f=>8, :d=>"foo"}}}
68

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

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

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