# Override Hash class with convience methods class Hash # Transform each key in Hash to a symbol. Privately used by non-self method def self.transform_keys_to_symbols(value) return value if not value.is_a?(Hash) hash = value.inject({}){|memo,(k,v)| memo[k.to_sym] = Hash.transform_keys_to_symbols(v); memo} return hash end # Take keys of hash and transform those to a symbols def transform_keys_to_symbols inject({}){|memo, (k, v)| memo[k.to_sym] = Hash.transform_keys_to_symbols(v); memo} end # Returns all keys that have a particular value within a nested Hash def find_all_values_for(key) result = [] result << self[key] self.values.each do |hash_value| # next if hash_value.is_a? Array # if hash_value.is_a?(Array) hash_value.each do |array_element| result += array_element.find_all_values_for(key) if array_element.is_a? Hash end end values = [hash_value] values.each do |value| result += value.find_all_values_for(key) if value.is_a? Hash end end result.compact end # Value present in nested Hash. 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 # # Whether key is present at least once # def include_key?(key) # result = find_all_values_for key # result != [] # end # Loop through each item within a key within a Hash if the key exists # @param [Key] key Key within hash to iterate through def each_if_not_null(key) case key.class.to_s when 'String' if self[key] self[key].each do |list_item| yield(list_item) end end when 'Array', 'Hash' if self[key[0]] if self[key[0]][key[1]] self[key[0]][key[1]].each do |list_item| yield(list_item) end end end end end end