Search code examples
rubyhashequalityordereddictionary

How to test order-conscious equality of 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

Solution

  • Probably the easiest is to compare the corresponding arrays.

    h1.to_a == h2.to_a