Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 326
Sparhawk Avatar asked Mar 06 '13 05:03

Sparhawk


People also ask

How do you know if two hashes are equal?

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.

Are hashes ordered?

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.


1 Answers

Probably the easiest is to compare the corresponding arrays.

h1.to_a == h2.to_a
like image 180
sawa Avatar answered Nov 15 '22 07:11

sawa