How to test order-conscious equality of hashes

大憨熊 提交于 2019-12-23 12:04:56

问题


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

回答1:


Probably the easiest is to compare the corresponding arrays.

h1.to_a == h2.to_a



回答2:


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.



来源:https://stackoverflow.com/questions/15239544/how-to-test-order-conscious-equality-of-hashes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!