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
Equality—Two hashes are equal if they each contain the same number of keys and if each key-value pair is equal to (according to Object#== ) the corresponding elements in the other hash. The orders of each hashes are not compared. Returns true if other is subset of hash.
An ordered hash is a compound data type that contains key-value pairs of different data types, including any mixture of scalars, arrays, structures, pointers, object references, dictionaries, lists, hashes, and other ordered hashes.
Probably the easiest is to compare the corresponding arrays.
h1.to_a == h2.to_a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With