Class: Hash

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

Instance Method Summary collapse

Instance Method Details

#deepen_hashObject


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/core_ext/hash_extend.rb', line 14

def deepen_hash
  self.inject(HashWithIndifferentAccess.new) do |result, (key, value)|
    path_names = key.split(".")
    if path_names.length == 1
      result[key] = value
    else
      key_result = path_names.reverse.inject(nil) do |result, path_name|
        if result == nil
          HashWithIndifferentAccess.new(path_name => value)
        else
          HashWithIndifferentAccess.new(path_name => result)
        end
      end
      result.deep_merge!(key_result)
    end
    result
  end
end

#difference(h2) ⇒ Object


33
34
35
# File 'lib/core_ext/hash_extend.rb', line 33

def difference(h2)
  dup.delete_if { |k, v| h2[k] == v }.merge!(h2.dup.delete_if { |k, v| has_key?(k) })
end

#flatten_hash(prefix = nil) ⇒ Object


2
3
4
5
6
7
8
9
10
11
12
# File 'lib/core_ext/hash_extend.rb', line 2

def flatten_hash(prefix = nil)
  self.inject(HashWithIndifferentAccess.new) do |result, (key, value)|
    combined_key = [prefix, key].compact.join(".")
    if value.is_a?(Hash)
      result.deep_merge!(value.flatten_hash(combined_key))
    else
      result[combined_key] = value
    end
    result
  end
end