我如何比较两个哈希? [英] How do I compare two hashes?

查看:25
本文介绍了我如何比较两个哈希?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

The output to the screen is the full file from file2. I know for a fact that the files are different, but the script doesn't seem to pick it up.

推荐答案

您可以直接比较哈希值是否相等:

You can compare hashes directly for equality:

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

<小时><小时>

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



You can convert the hashes to arrays, then get their difference:

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}

<小时>

进一步简化:


Simplifying further:

通过三元结构分配差异:

Assigning difference via a ternary structure:

  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变量:

Doing it all in one operation and getting rid of the difference variable:

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

这篇关于我如何比较两个哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆