Class: Hash

Inherits:
Object show all
Defined in:
lib/Hash.rb

Overview

hash extend deep_merge

Instance Method Summary collapse

Instance Method Details

#deep_merge(other_hash) ⇒ Object

Returns a new hash with self and other_hash merged recursively.



4
5
6
# File 'lib/Hash.rb', line 4

def deep_merge(other_hash)
  dup.deep_merge!(other_hash)
end

#deep_merge!(other_hash) ⇒ Object

Same as deep_merge, but modifies self.



9
10
11
12
13
14
15
# File 'lib/Hash.rb', line 9

def deep_merge!(other_hash)
  other_hash.each_pair do |k,v|
    tv = self[k]
    self[k] = tv.is_a?(Hash) && v.is_a?(Hash) ? tv.deep_merge(v) : v
  end
  self
end

#join_keys(str = ".", key = "") ⇒ Object



17
18
19
# File 'lib/Hash.rb', line 17

def join_keys( str = ".", key="" )
  dup.join_keys! str, key
end

#join_keys!(str = ".", key = "") ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/Hash.rb', line 21

def join_keys!( str = ".", key="")
  res = {}
  each do |k, v|
    full_key = key.empty? ?  k : "#{key}#{str}#{k}"
    if v.is_a?(Hash)
      res.deep_merge!( v.join_keys( str, full_key ) )
    else
      res[full_key] = v
    end
  end

  clear
  self.merge! res
end