Class: HashUtils

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

Class Method Summary collapse

Class Method Details

.deep_stringify_keys(hash) ⇒ Object

Convert keys to strings, recursively



24
25
26
27
28
# File 'lib/hash.rb', line 24

def self.deep_stringify_keys(hash)
  transform_hash(hash, deep: true) do |hash, key, value|
    hash[key.to_s] = value
  end
end

.transform_hash(original, options = {}, &block) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/hash.rb', line 4

def self.transform_hash(original, options = {}, &block)
  original.each_with_object({}) do |(key, value), result|
    value = if options[:deep] && value.is_a?(Hash)
              transform_hash(value, options, &block)
            elsif value.is_a?(Array)
              value.map do |v|
                if v.is_a?(Hash)
                  transform_hash(v, options, &block)
                else
                  v
                end
              end
            else
              value
            end
    block.call(result, key, value)
  end
end