How do I compare two hashes?

前端 未结 14 1470
粉色の甜心
粉色の甜心 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:51

    If you need a quick and dirty diff between hashes which correctly supports nil in values you can use something like

    def diff(one, other)
      (one.keys + other.keys).uniq.inject({}) do |memo, key|
        unless one.key?(key) && other.key?(key) && one[key] == other[key]
          memo[key] = [one.key?(key) ? one[key] : :_no_key, other.key?(key) ? other[key] : :_no_key]
        end
        memo
      end
    end
    
    0 讨论(0)
  • 2020-11-30 00:51

    I developed this to compare if two hashes are equal

    def hash_equal?(hash1, hash2)
      array1 = hash1.to_a
      array2 = hash2.to_a
      (array1 - array2 | array2 - array1) == []
    end
    

    The usage:

    > hash_equal?({a: 4}, {a: 4})
    => true
    > hash_equal?({a: 4}, {b: 4})
    => false
    
    > hash_equal?({a: {b: 3}}, {a: {b: 3}})
    => true
    > hash_equal?({a: {b: 3}}, {a: {b: 4}})
    => false
    
    > hash_equal?({a: {b: {c: {d: {e: {f: {g: {h: 1}}}}}}}}, {a: {b: {c: {d: {e: {f: {g: {h: 1}}}}}}}})
    => true
    > hash_equal?({a: {b: {c: {d: {e: {f: {g: {marino: 1}}}}}}}}, {a: {b: {c: {d: {e: {f: {g: {h: 2}}}}}}}})
    => false
    
    0 讨论(0)
提交回复
热议问题