如何比较两个散列?


108

我正在尝试使用以下代码比较两个Ruby哈希:

#!/usr/bin/env ruby

require "yaml"
require "active_support"

file1 = YAML::load(File.open('./en_20110207.yml'))
file2 = YAML::load(File.open('./locales/en.yml'))

arr = []

file1.select { |k,v|
  file2.select { |k2, v2|
    arr << "#{v2}" if "#{v}" != "#{v2}"
  }
}

puts arr

屏幕上的输出是file2中的完整文件。我知道文件是不同的,但是脚本似乎并没有选择它。


Answers:


161

您可以直接比较散列是否相等:

hash1 = {'a' => 1, 'b' => 2}
hash2 = {'a' => 1, 'b' => 2}
hash3 = {'a' => 1, 'b' => 2, 'c' => 3}

hash1 == hash2 # => true
hash1 == hash3 # => false

hash1.to_a == hash2.to_a # => true
hash1.to_a == hash3.to_a # => false


您可以将散列转换为数组,然后得到它们的区别:

hash3.to_a - hash1.to_a # => [["c", 3]]

if (hash3.size > hash1.size)
  difference = hash3.to_a - hash1.to_a
else
  difference = hash1.to_a - hash3.to_a
end
Hash[*difference.flatten] # => {"c"=>3}

进一步简化:

通过三元结构分配差异:

  difference = (hash3.size > hash1.size) \
                ? hash3.to_a - hash1.to_a \
                : hash1.to_a - hash3.to_a
=> [["c", 3]]
  Hash[*difference.flatten] 
=> {"c"=>3}

一次完成所有操作并摆脱difference变量:

  Hash[*(
  (hash3.size > hash1.size)    \
      ? hash3.to_a - hash1.to_a \
      : hash1.to_a - hash3.to_a
  ).flatten] 
=> {"c"=>3}

3
无论如何,有没有得到两者之间的差异?
dennismonsewicz 2011年

5
哈希值可以相同,但包含不同的值。在这种情况下,hash1.to_a - hash3.to_aand和 hash3.to_a - hash1.to_a可能会返回非空值hash1.size == hash3.size。仅当散列大小不同时,EDIT之后的部分才有效。
ohaleck 2014年

3
很好,但是应该在以后退出。A.size> B.size不一定意味着A包含B。仍然需要取对称差的并集。
基因

.to_a当相等的哈希具有不同顺序的密钥时,直接比较will 的输出将失败:{a:1, b:2} == {b:2, a:1}=> true,{a:1, b:2}.to_a == {b:2, a:1}.to_a=> false
aidan

flatten和的目的是*什么?为什么不只是Hash[A.to_a - B.to_a]
JeremyKun

34

您可以尝试使用hashdiff gem,它可以对散列中的哈希和数组进行深度比较。

以下是一个示例:

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]]

4
我有一些相当深的哈希值,导致测试失败。通过将替换为got_hash.should eql expected_hashHashDiff.diff(got_hash, expected_hash).should eql []我现在获得了显示我确切需要的输出。完善!
davetapley

哇,HashDiff很棒。尝试快速查看巨大的嵌套JSON数组中发生了什么更改。谢谢!
Jeff Wigal 2014年

你的宝石真棒!在编写涉及JSON操作的规范时非常有用。谢谢。
阿兰2015年

2
我对HashDiff的经验是,它对于较小的散列非常有效,但是diff速度似乎无法很好地扩展。如果您希望对它的调用进行基准测试,那么如果它可能会被喂入两个大的哈希值,并确保差异时间在您的承受能力之内,则值得进行基准测试。
David Bodow

使用该use_lcs: false标志可以显着加快大型散列的比较:Hashdiff.diff(b, a, use_lcs: false)
Eric Walker

15

如果要获取两个哈希之间的区别,可以执行以下操作:

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"}

12

Rails正在弃用diff方法。

快速的单线:

hash1.to_s == hash2.to_s

我总是忘记这一点。可以轻松使用许多相等检查to_s
Tin Man

17
当相等的哈希具有不同顺序的密钥时,它将失败:{a:1, b:2} == {b:2, a:1}=> true,{a:1, b:2}.to_s == {b:2, a:1}.to_s=> false
aidan

2
这是一个功能!:D
戴夫·摩尔斯

5

您可以使用简单的数组交集,通过这种方式,您可以知道每个哈希的区别。

    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


1

如果您需要在散列之间快速且肮脏的差异正确地支持零值,则可以使用类似

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

1

如果您需要格式正确的diff,可以执行以下操作:

# Gemfile
gem 'awesome_print' # or gem install awesome_print

在您的代码中:

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})

这个想法是使用很棒的打印来格式化和比较输出。diff并不精确,但是对于调试目的很有用。


1

...,现在以模块形式应用于各种集合类(其中的哈希)。这不是深入的检查,但很简单。

# 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

1

我开发了此方法以比较两个哈希是否相等

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

用法:

> 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

既将hash转换为_json又作为字符串比较怎么办?但请记住

require "json"
h1 = {a: 20}
h2 = {a: "20"}

h1.to_json==h1.to_json
=> true
h1.to_json==h2.to_json
=> false

0

这是深度比较两个哈希的算法,它们还将比较嵌套数组:

    HashDiff.new(
      {val: 1, nested: [{a:1}, {b: [1, 2]}] },
      {val: 2, nested: [{a:1}, {b: [1]}] }
    ).report
# Output:
val:
- 1
+ 2
nested > 1 > b > 1:
- 2

实现方式:

class HashDiff

  attr_reader :left, :right

  def initialize(left, right, config = {}, path = nil)
    @left  = left
    @right = right
    @config = config
    @path = path
    @conformity = 0
  end

  def conformity
    find_differences
    @conformity
  end

  def report
    @config[:report] = true
    find_differences
  end

  def find_differences
    if hash?(left) && hash?(right)
      compare_hashes_keys
    elsif left.is_a?(Array) && right.is_a?(Array)
      compare_arrays
    else
      report_diff
    end
  end

  def compare_hashes_keys
    combined_keys.each do |key|
      l = value_with_default(left, key)
      r = value_with_default(right, key)
      if l == r
        @conformity += 100
      else
        compare_sub_items l, r, key
      end
    end
  end

  private

  def compare_sub_items(l, r, key)
    diff = self.class.new(l, r, @config, path(key))
    @conformity += diff.conformity
  end

  def report_diff
    return unless @config[:report]

    puts "#{@path}:"
    puts "- #{left}" unless left == NO_VALUE
    puts "+ #{right}" unless right == NO_VALUE
  end

  def combined_keys
    (left.keys + right.keys).uniq
  end

  def hash?(value)
    value.is_a?(Hash)
  end

  def compare_arrays
    l, r = left.clone, right.clone
    l.each_with_index do |l_item, l_index|
      max_item_index = nil
      max_conformity = 0
      r.each_with_index do |r_item, i|
        if l_item == r_item
          @conformity += 1
          r[i] = TAKEN
          break
        end

        diff = self.class.new(l_item, r_item, {})
        c = diff.conformity
        if c > max_conformity
          max_conformity = c
          max_item_index = i
        end
      end or next

      if max_item_index
        key = l_index == max_item_index ? l_index : "#{l_index}/#{max_item_index}"
        compare_sub_items l_item, r[max_item_index], key
        r[max_item_index] = TAKEN
      else
        compare_sub_items l_item, NO_VALUE, l_index
      end
    end

    r.each_with_index do |item, index|
      compare_sub_items NO_VALUE, item, index unless item == TAKEN
    end
  end

  def path(key)
    p = "#{@path} > " if @path
    "#{p}#{key}"
  end

  def value_with_default(obj, key)
    obj.fetch(key, NO_VALUE)
  end

  module NO_VALUE; end
  module TAKEN; end

end

-3

如何使用另一种更简单的方法:

require 'fileutils'
FileUtils.cmp(file1, file2)

2
仅在您需要哈希在磁盘上相同时,这才有意义。磁盘上的两个文件不同,这是因为hash元素的顺序不同,它们仍然可以包含相同的元素,并且就Ruby而言,一旦加载它们就相等。
Tin Man
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.