Sha256: a6b3fbc4797f68c75405f5248125eed8ee34c20c6b9661a8829422665e317f5f

Contents?: true

Size: 715 Bytes

Versions: 1

Compression:

Stored size: 715 Bytes

Contents

module BabelDiff
  class HashFlattener < Struct.new(:hash)
    def flat_hash
      @_flat_hash ||= {}
    end

    def flatten(current_hash = hash, keys = [])
      current_hash.each do |key, value|
        new_keys = keys.dup << key
        if value.is_a? Hash
          flatten(value, new_keys)
        else
          flat_hash[new_keys.join(".")] = value
        end
      end
      flat_hash
    end

    def unflatten
      {}.tap do |unflattened_hash|
        hash.each do |k,v|
          keys = k.split(".")
          current_hash = unflattened_hash

          keys[0...-1].each { |key| current_hash = current_hash[key] ||= {} }

          current_hash[keys.last] = v
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
babel_diff-1.1.0 lib/babel_diff/hash_flattener.rb