Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/core_ext.rb

Overview

Here we add some methods better work with Tries

Instance Method Summary collapse

Instance Method Details

#clone_values(from_keys: nil, to_keys: nil, suffix: nil, branch_a: nil, branch_b: nil) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/core_ext.rb', line 40

def clone_values(from_keys: nil,
                 to_keys: nil,
                 suffix: nil,
                 branch_a: nil,
                 branch_b: nil)

  branch_a ||= dig(*from_keys)
  if branch_b.nil?
    create_branch!(*to_keys)
    branch_b = dig(*to_keys)
  end

  branch_a.each do |key, val|
    if val.is_a?(Hash)
      clone_values branch_a: branch_a[key],
                   branch_b: (branch_b[key] ||= {}),
                   suffix: suffix
    else
      branch_b[key] = "#{val.dup}#{suffix}"
    end
  end
end

#create_branch!(*keys) ⇒ Object



63
64
65
66
67
# File 'lib/core_ext.rb', line 63

def create_branch!(*keys)
  return nil if keys.empty?
  key = keys.shift
  (self[key] ||= {}).create_branch!(*keys)
end

#deep_dupObject



69
70
71
72
73
74
75
76
77
78
79
# File 'lib/core_ext.rb', line 69

def deep_dup
  dup_hash = {}
  each do |k, v|
    dup_hash[k] = if v.is_a?(Hash)
                    v.deep_dup
                  else
                    v.dup
                  end
  end
  dup_hash
end

#dig(*args) ⇒ Object



36
37
38
# File 'lib/core_ext.rb', line 36

def dig(*args)
  args.size > 1 ? self[args.shift].dig(*args) : self[args[0]]
end