How do I compare two hashes?

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

    If you want to get what is the difference between two hashes, you can do this:

    h1 = {:a => 20, :b => 10, :c => 44}
    h2 = {:a => 2, :b => 10, :c => "44"}
    result = {}
    h1.each {|k, v| result[k] = h2[k] if h2[k] != v }
    p result #=> {:a => 2, :c => "44"}
    
    0 讨论(0)
  • 2020-11-30 00:37

    Rails is deprecating the diff method.

    For a quick one-liner:

    hash1.to_s == hash2.to_s
    
    0 讨论(0)
  • 2020-11-30 00:37

    How about another, simpler approach:

    require 'fileutils'
    FileUtils.cmp(file1, file2)
    
    0 讨论(0)
  • 2020-11-30 00:41

    You can try the hashdiff gem, which allows deep comparison of hashes and arrays in the hash.

    The following is an example:

    a = {a:{x:2, y:3, z:4}, b:{x:3, z:45}}
    b = {a:{y:3}, b:{y:3, z:30}}
    
    diff = HashDiff.diff(a, b)
    diff.should == [['-', 'a.x', 2], ['-', 'a.z', 4], ['-', 'b.x', 3], ['~', 'b.z', 45, 30], ['+', 'b.y', 3]]
    
    0 讨论(0)
  • 2020-11-30 00:41

    You could use a simple array intersection, this way you can know what differs in each hash.

        hash1 = { a: 1 , b: 2 }
        hash2 = { a: 2 , b: 2 }
    
        overlapping_elements = hash1.to_a & hash2.to_a
    
        exclusive_elements_from_hash1 = hash1.to_a - overlapping_elements
        exclusive_elements_from_hash2 = hash2.to_a - overlapping_elements
    
    0 讨论(0)
  • 2020-11-30 00:44

    If you want a nicely formatted diff, you can do this:

    # Gemfile
    gem 'awesome_print' # or gem install awesome_print
    

    And in your code:

    require 'ap'
    
    def my_diff(a, b)
      as = a.ai(plain: true).split("\n").map(&:strip)
      bs = b.ai(plain: true).split("\n").map(&:strip)
      ((as - bs) + (bs - as)).join("\n")
    end
    
    puts my_diff({foo: :bar, nested: {val1: 1, val2: 2}, end: :v},
                 {foo: :bar, n2: {nested: {val1: 1, val2: 3}}, end: :v})
    

    The idea is to use awesome print to format, and diff the output. The diff won't be exact, but it is useful for debugging purposes.

    0 讨论(0)
提交回复
热议问题