【发布时间】:2020-03-13 23:04:29
【问题描述】:
我陷入了这样的问题。我有 2 个哈希值,我试图在 rspec 测试中进行比较:
describe 'sort tests' do
let(:actual) do
{
1 => { users: { 1 => { id: 1,
accounts: [1],
profit: 10,
revenue: 1,
loss: 9 },
2 => { id: 2,
accounts: [2, 3, 6],
profit: -24,
revenue: 6,
loss: -30 } },
total_profit: -14,
total_revenue: 7,
total_loss: -21 },
2 => { users: { 3 => { id: 3,
accounts: [4, 5],
profit: 27,
revenue: 9,
loss: 18 } },
total_profit: 27,
total_revenue: 9,
total_loss: 18 }
}
end
let(:expected) do
{
1 => { users: { 2 => { id: 2,
accounts: [2, 3, 6],
profit: -24,
revenue: 6,
loss: -30 },
1 => { id: 1,
accounts: [1],
profit: 10,
revenue: 1,
loss: 9 } },
total_profit: -14,
total_revenue: 7,
total_loss: -21 },
2 => { users: { 3 => { id: 3,
accounts: [4, 5],
profit: 27,
revenue: 9,
loss: 18 } },
total_profit: 27,
total_revenue: 9,
total_loss: 18 }
}
end
it 'sort' do
def mysort(data)
data.each do |_, partner|
partner[:users].sort_by { |_k, user| user[:loss] }.to_h
partner
end
data.sort_by { |_, partner| partner[:total_loss] }.to_h
end
expect(mysort(actual)).to eql expected
# expect(Digest::MD5.hexdigest(Marshal::dump(mysort(actual)))).to eql Digest::MD5.hexdigest(Marshal::dump(expected))
end
end
测试通过了。但是,如果我取消注释 md5 检查,它将引发哈希不同的错误:
expected: "155d27d209f286fb1fc9ebeb0dcd6d3d"
got: "255df98d4fc8166d0d8ffc7227ffd351"
所以,eql 实际上并没有正确比较哈希值,并且 mysort 函数中存在错误:
def mysort(data)
data.each do |_, partner|
partner[:users] = partner[:users].sort_by { |_k, user| user[:loss] }.to_h
partner
end
data.sort_by { |_, partner| partner[:total_loss] }.to_h
end
现在排序正常,但仅比较 md5 校验和有助于了解哈希是否相等:(
如何在没有这个 hack 的情况下比较哈希?
【问题讨论】:
-
"eql 实际上没有正确比较哈希",这取决于您要如何比较。对于大多数情况,这是首选行为。因为键值对的顺序在大多数情况下并不重要。 documentation 声明 “相等——如果两个散列都包含相同数量的键,并且每个键值对等于(根据
Object#==)另一个散列中的相应元素,则它们是相等的。” 但是通过问题猜测您还想比较键的顺序? -
是的。我也想比较一下哈希的顺序。
标签: ruby multidimensional-array hash rspec