Sha256: d66fe8ce1d6984c5486b204d0a309b32af8114680dfa0bde98e82c5fbece013d

Contents?: true

Size: 798 Bytes

Versions: 18

Compression:

Stored size: 798 Bytes

Contents

class DynportTools::DeepMerger
  class << self
    def merge(a, b)
      if a.is_a?(Hash) && b.is_a?(Hash)
        merge_hashes(a, b)
      elsif a.is_a?(Array) && b.is_a?(Array)
        merge_arrays(a, b)
      else
        b
      end
    end
    
    def merge_arrays(a, b)
      [a.length, b.length].max.times.map do |i|
        if b.length < i + 1
          a[i]
        elsif a.length < i + 1
          b[i]
        else
          merge(a[i], b[i])
        end
      end
    end
    
    def merge_hashes(a, b)
      (a.keys + b.keys).uniq.inject({}) do |hash, key|
        if !a.has_key?(key)
          hash[key] = b[key]
        elsif !b.has_key?(key)
          hash[key] = a[key]
        else
          hash[key] = merge(a[key], b[key])
        end
        hash
      end
    end
  end
end

Version data entries

18 entries across 18 versions & 1 rubygems

Version Path
dynport_tools-0.2.22 lib/dynport_tools/deep_merger.rb
dynport_tools-0.2.21 lib/dynport_tools/deep_merger.rb
dynport_tools-0.2.20 lib/dynport_tools/deep_merger.rb
dynport_tools-0.2.19 lib/dynport_tools/deep_merger.rb
dynport_tools-0.2.18 lib/dynport_tools/deep_merger.rb
dynport_tools-0.2.17 lib/dynport_tools/deep_merger.rb
dynport_tools-0.2.16 lib/dynport_tools/deep_merger.rb
dynport_tools-0.2.15 lib/dynport_tools/deep_merger.rb
dynport_tools-0.2.14 lib/dynport_tools/deep_merger.rb
dynport_tools-0.2.13 lib/dynport_tools/deep_merger.rb
dynport_tools-0.2.12 lib/dynport_tools/deep_merger.rb
dynport_tools-0.2.11 lib/dynport_tools/deep_merger.rb
dynport_tools-0.2.10 lib/dynport_tools/deep_merger.rb
dynport_tools-0.2.9 lib/dynport_tools/deep_merger.rb
dynport_tools-0.2.8 lib/dynport_tools/deep_merger.rb
dynport_tools-0.2.6 lib/dynport_tools/deep_merger.rb
dynport_tools-0.2.5 lib/dynport_tools/deep_merger.rb
dynport_tools-0.2.4 lib/dynport_tools/deep_merger.rb