Class: Hash

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

Overview

Override Hash class with convenience methods

Direct Known Subclasses

IndifferentHash

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.transform_keys_to_symbols(value) ⇒ Object

Transform each key in Hash to a symbol. Privately used by non-self method

Parameters:

  • value (Object)

    Value inside hash to transform keys under



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

def self.transform_keys_to_symbols(value)
  return value unless value.is_a?(Hash)

  hash = value.each_with_object({}) { |(k, v), memo| memo[k.to_sym] = Hash.transform_keys_to_symbols(v); }
  hash
end

Instance Method Details

#include_value?(value) ⇒ Boolean

Value present in nested Hash.

Examples:

hash = { a: { b: 25 }, c: 3 }
hash.include_value?(25) #=> true

Returns:

  • (Boolean)

    Whether value is included in nested Hash



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/soaspec/core_ext/hash.rb', line 28

def include_value?(value)
  each_value do |v|
    return true if v == value
    next unless v.is_a? Hash

    v.each_value do |v|
      return true if v == value
      next unless v.is_a? Hash

      v.each_value do |v|
        return true if v == value
      end
    end
  end
  false
end

#transform_keys_to_symbolsHash

Take keys of hash and transform those to a symbols

Examples:

hash = { 'a' => 1, 'b' => { c: 4 } }
hash.transform_keys_to_symbols # => { a: 1, b: { c: 4 } }

Returns:

  • (Hash)

    Hash will all keys converted to symbols



19
20
21
# File 'lib/soaspec/core_ext/hash.rb', line 19

def transform_keys_to_symbols
  each_with_object({}) { |(k, v), memo| memo[k.to_sym] = Hash.transform_keys_to_symbols(v); }
end