How to check for conscious hash equality

Ruby 1.9.2 introduces hash order. How can I check two hashes for equality in order based order?

Given:

h1 = {"a"=>1, "b"=>2, "c"=>3} h2 = {"a"=>1, "c"=>3, "b"=>2} 

I need a comparison operator that returns false for h1 and h2 . None of the following work:

 h1 == h2 # => true h1.eql? h2 # => true 
+4
source share
2 answers

You can compare the output of your 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 ordering key input is strange. Depending on what you are trying to do, you may want to revise your underlying data structure.

+4
source

It is probably easiest to compare the corresponding arrays.

 h1.to_a == h2.to_a 
+6
source

All Articles