How do I compare two hashes?

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

    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
    

提交回复
热议问题