Class: Hash
Overview
:nodoc:
Instance Method Summary collapse
-
#deep_find(key, uniq: true) ⇒ Object
Hash#deep_find -> value.
Instance Method Details
#deep_find(key, uniq: true) ⇒ Object
TODO:
change uniq true to uniq false
Hash#deep_find -> value
This method is an extension for Hash core class to search for a value of a key in N-nested hash. It provides search for multiple values if key appears more than once. For e.g.:
If values are identical, they will be returned in a single copy. You can disable this feature with special param uniq
, which is true
by default. For e.g.:
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/extensions/deep_find.rb', line 27 def deep_find(key, uniq: true) result = [] result << self[key] each_value do |hash_value| values = hash_value.is_a?(Array) ? hash_value : [hash_value] values.each do |value| result << value.deep_find(key) if value.is_a? Hash end end result = result.compact.delete_if do |i| i.is_a?(Array) && i.empty? end result.uniq! if uniq result.size == 1 ? result.first : result end |