如何测试散列顺序意识的平等 [英] How to test order-conscious equality of hashes
本文介绍了如何测试散列顺序意识的平等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
鉴于:
h1 = {a=> 1,b=> 2,c=> 3}
h2 = {a=> 1,c=> ; 3,b=> 2}
我想要一个返回 false
为 h1
和 h2
。以下任何一项都无效:
h1 == h2#=>真
h1.eql? h2#=> true
解决方案
您可以比较
方法:
h1 = {one:1,two:2,three: 3}#=> {:one => 1,:two => 2,:three => 3}
h2 = {three:3,one:1,two:2}#=> {:three => 3,:one => 1,:two => 2}
h1 == h2#=> true
h1.keys#=> [:one,:two,:three]
h2.keys#=> [:three,:one,:two]
h1.keys.sort == h2.keys.sort#=> true
h1.keys == h2.keys#=>假
但是,根据密钥插入顺序比较Hashes有点奇怪。取决于你想要做什么,你可能想重新考虑你的基础数据结构。
Ruby 1.9.2 introduced order into hashes. How can I test two hashes for equality considering the order?
Given:
h1 = {"a"=>1, "b"=>2, "c"=>3}
h2 = {"a"=>1, "c"=>3, "b"=>2}
I want a comparison operator that returns false
for h1
and h2
. Neither of the followings work:
h1 == h2 # => true
h1.eql? h2 # => true
解决方案
You could compare the output of their keys
methods:
h1 = {one: 1, two: 2, three: 3} # => {:one=>1, :two=>2, :three=>3}
h2 = {three: 3, one: 1, two: 2} # => {:three=>3, :one=>1, :two=>2}
h1 == h2 # => true
h1.keys # => [:one, :two, :three]
h2.keys # => [:three, :one, :two]
h1.keys.sort == h2.keys.sort # => true
h1.keys == h2.keys # => false
But, comparing Hashes based on key insertion order is kind of strange. Depending on what exactly you're trying to do, you may want to reconsider your underlying data structure.
这篇关于如何测试散列顺序意识的平等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文