How do I compare two hashes?

前端 未结 14 1562
粉色の甜心
粉色の甜心 2020-11-30 00:06

I am trying to compare two Ruby Hashes using the following code:

#!/usr/bin/env ruby

require \"yaml\"
require \"active_support\"

file1 = YAML::load(File.op         


        
14条回答
  •  孤独总比滥情好
    2020-11-30 00:46

    ... and now in module form to be applied to a variety of collection classes (Hash among them). It's not a deep inspection, but it's simple.

    # Enable "diffing" and two-way transformations between collection objects
    module Diffable
      # Calculates the changes required to transform self to the given collection.
      # @param b [Enumerable] The other collection object
      # @return [Array] The Diff: A two-element change set representing items to exclude and items to include
      def diff( b )
        a, b = to_a, b.to_a
        [a - b, b - a]
      end
    
      # Consume return value of Diffable#diff to produce a collection equal to the one used to produce the given diff.
      # @param to_drop [Enumerable] items to exclude from the target collection
      # @param to_add  [Enumerable] items to include in the target collection
      # @return [Array] New transformed collection equal to the one used to create the given change set
      def apply_diff( to_drop, to_add )
        to_a - to_drop + to_add
      end
    end
    
    if __FILE__ == $0
      # Demo: Hashes with overlapping keys and somewhat random values.
      Hash.send :include, Diffable
      rng = Random.new
      a = (:a..:q).to_a.reduce(Hash[]){|h,k| h.merge! Hash[k, rng.rand(2)] }
      b = (:i..:z).to_a.reduce(Hash[]){|h,k| h.merge! Hash[k, rng.rand(2)] }
      raise unless a == Hash[ b.apply_diff(*b.diff(a)) ] # change b to a
      raise unless b == Hash[ a.apply_diff(*a.diff(b)) ] # change a to b
      raise unless a == Hash[ a.apply_diff(*a.diff(a)) ] # change a to a
      raise unless b == Hash[ b.apply_diff(*b.diff(b)) ] # change b to b
    end
    

提交回复
热议问题