Module: Scalyr::Common::Util
- Defined in:
- lib/scalyr/common/util.rb
Class Method Summary collapse
-
.flatten(obj, delimiter = '_') ⇒ Object
Flattens a hash or array, returning a hash where keys are a delimiter-separated string concatenation of all nested keys.
Class Method Details
.flatten(obj, delimiter = '_') ⇒ Object
Flattens a hash or array, returning a hash where keys are a delimiter-separated string concatenation of all nested keys. Returned keys are always strings. If a non-hash or array is provided, raises TypeError. Please see rspec util_spec.rb for expected behavior.
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/scalyr/common/util.rb', line 7 def self.flatten(obj, delimiter='_') # base case is input object is not enumerable, in which case simply return it if !obj.respond_to?(:each) raise TypeError.new('Input must be a hash or array') end result = Hash.new # require 'pry' # binding.pry if obj.respond_to?(:has_key?) # input object is a hash obj.each do |key, value| if value.respond_to?(:each) flatten(value).each do |subkey, subvalue| result["#{key}#{delimiter}#{subkey}"] = subvalue end else result["#{key}"] = value end end else # input object is an array or set obj.each_with_index do |value, index| if value.respond_to?(:each) flatten(value).each do |subkey, subvalue| result["#{index}#{delimiter}#{subkey}"] = subvalue end else result["#{index}"] = value end end end return result end |