class Hash
Hash
class additions
Over time these may get depreciated in favor of other solutions.
Public Instance Methods
search(search_key, options = {})
click to toggle source
Search for a key (potentially recursively) in a given hash.
This method uses strict matching between string and symbol key types. They must be the same type or they will not match.
-
Parameters
- String, Symbol
-
search_key Key to search for in hash
Hash
<String, Symbol|ANY>-
options Search options
- Boolean
-
:recurse Whether to recurse through sub hashes to find key value
- Integer
-
:recurse_level Maximum level to recurse into nested hashes or -1 for all
-
Returns
- ANY
-
Return value for search key if value found, nil otherwise
-
Errors
See also:
# File lib/core/mod/hash.rb 27 def search(search_key, options = {}) 28 config = Nucleon::Config.ensure(options) 29 value = nil 30 31 recurse = config.get(:recurse, false) 32 recurse_level = config.get(:recurse_level, -1) 33 34 self.each do |key, data| 35 if key == search_key 36 value = data 37 38 elsif data.is_a?(Hash) && 39 recurse && (recurse_level == -1 || recurse_level > 0) 40 41 recurse_level -= 1 unless recurse_level == -1 42 value = value.search(search_key, 43 Nucleon::Config.new(config).set(:recurse_level, recurse_level) 44 ) 45 end 46 break unless value.nil? 47 end 48 return value 49 end