Class: Hash

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

Overview

author: Dominik Richter author: Christoph Hartmann

Instance Method Summary collapse

Instance Method Details

#contains(contains) ⇒ Object

deep check if all values are contained



32
33
34
35
36
37
38
39
40
# File 'lib/utils/hash.rb', line 32

def contains(contains)
  hash = smash
  contains = contains.smash

  contains.each do |key, val|
    return false if hash[key] != val
  end
  true
end

#deep_merge(second) ⇒ Object



7
8
9
10
11
12
# File 'lib/utils/hash.rb', line 7

def deep_merge(second)
  merger = proc { |_key, v1, v2|
    v1.is_a?(Hash) && v2.is_a?(Hash) ? v1.merge(v2, &merger) : v2
  }
  merge(second, &merger)
end

#smash(prefix = nil) ⇒ Object

converts a deep hash into a flat hash hash =

'a' => 1,
'b' => {'c' => 2,

} hash.smash # => {“a”=>1, “b-c”=>2}



20
21
22
23
24
25
26
27
28
29
# File 'lib/utils/hash.rb', line 20

def smash(prefix = nil)
  inject({}) do |acc, (key, value)|
    index = prefix.to_s + key.to_s
    if value.is_a?(Hash)
      acc.merge(value.smash(index + '-'))
    else
      acc.merge(index => value)
    end
  end
end