Sha256: dad9f4b70bf5e6489b501b97d02207495b544b25946693bc28483999608753d9

Contents?: true

Size: 994 Bytes

Versions: 1

Compression:

Stored size: 994 Bytes

Contents

require "celsius"

module Celsius::Hash
  #
  # This module provides some helper functions for dealing with hashes
  #
  def self.deep_find_key(object, key)
    results = []

    if key.is_a?(Array)
      key.inject(object) do |memo, key_element|
        deep_find_key(memo, key_element)
      end
    else
      if object.is_a?(Array)
        # flatten(1) prevents unintend array nesting due to recursion
        results.concat object.map { |value| deep_find_key(value, key) }.flatten(1)
      elsif object.is_a?(Hash)
        if object.has_key?(key.to_s) || object.has_key?(key.to_sym)
          results << (object[key.to_s] || object[key.to_sym])
        else
          # its easier to concat an empty array than checking for nil
          results.concat deep_find_key(object.values, key) || []
        end
      end

      # remove nils
      results.compact!

      # in case nothing was found, return nil to ease detecting this case
      results.empty? ? nil : results
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
celsius-0.4.0 lib/celsius/hash.rb