如何测试秩序意识的哈希平等
Ruby 1.9.2将顺序引入哈希。 考虑到顺序,我如何测试两个哈希值是否相等?
鉴于:
h1 = {"a"=>1, "b"=>2, "c"=>3} h2 = {"a"=>1, "c"=>3, "b"=>2}
我想要一个比较运算符,它为h1
和h2
返回false
。 以下两点都不起作用:
h1 == h2 # => true h1.eql? h2 # => true
您可以比较其keys
方法的输出:
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
但是,根据键插入顺序比较Hashes有点奇怪。 根据您的具体操作,您可能需要重新考虑基础数据结构。
可能最简单的方法是比较相应的数组。
h1.to_a == h2.to_a