두 해시를 어떻게 비교합니까?


108

다음 코드를 사용하여 두 개의 Ruby Hashe를 비교하려고합니다.

#!/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의 전체 파일입니다. 나는 파일이 다르다는 사실을 알고 있지만 스크립트가 그것을 선택하지 않는 것 같습니다.


의 중복 가능성 비교 루비 해시
제프 Lanotte

답변:


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

5
해시는 같은 크기 일 수 있지만 다른 값을 포함 할 수 있습니다. 이 경우 모두 hash1.to_a - hash3.to_ahash3.to_a - hash1.to_a비어 있지 않은 값을 반환 할 수 있습니다 hash1.size == hash3.size. EDIT 이후의 부분 은 해시 크기가 다른 경우에만 유효합니다.
ohaleck 2014 년

3
좋지만 그만 두어야합니다. A.size> B.size는 반드시 A에 B가 포함된다는 것을 의미하지는 않습니다. 여전히 대칭 적 차이를 합쳐야합니다.
Gene

.to_a동일한 해시가 다른 순서로 키를 가질 때 출력을 직접 비교하는 것은 실패합니다 : {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 2012-07-24

와, HashDiff는 굉장합니다. 거대한 중첩 JSON 배열에서 변경된 사항을 확인하는 작업을 빠르게 수행했습니다. 감사!
제프 Wigal

당신의 보석은 굉장합니다! JSON 조작과 관련된 사양을 작성할 때 매우 유용합니다. 고마워.
Alain

2
HashDiff에 대한 내 경험은 작은 해시에서 정말 잘 작동하지만 diff 속도가 잘 확장되지 않는 것 같습니다. 두 개의 큰 해시가 제공 될 것으로 예상되는 경우 호출을 벤치마킹하고 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.
The 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
Dave Morse

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

값에서 nil을 올바르게 지원하는 해시 간의 빠르고 더러운 diff가 필요하면 다음과 같은 것을 사용할 수 있습니다.

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

아이디어는 멋진 인쇄물을 사용하여 형식을 지정하고 출력을 비교하는 것입니다. 차이는 정확하지 않지만 디버깅 목적으로 유용합니다.


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

해시를 _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
디스크에서 해시가 동일해야하는 경우에만 의미가 있습니다. 해시 요소의 순서가 다르기 때문에 디스크에서 다른 두 파일은 여전히 ​​동일한 요소를 포함 할 수 있으며 일단로드되면 Ruby가 고려하는 한 동일합니다.
틴 남자
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.