Fwd: Comparing hashes based on their keys

1st send attempt died in spamassassin…

---------- Forwarded message ----------
From: Robert K. [email protected]
Date: Sat, Jul 16, 2011 at 12:21 AM
Subject: Re: Comparing hashes based on their keys
To: [email protected]

On Fri, Jul 15, 2011 at 9:47 PM, Rob B.
[email protected] wrote:

self[].same_key_structure?(other[]) : !other[_].is_a?(Hash)}

In other words, I consider these two hashes to be equal:

h1 = {:x => nil, :y => nil}
h2 = {:y => nil, :x => nil}

but h1.keys == h2.keys would return false in this context.

then sort them:

return false unless self.keys.sort == other.keys.sort

There is one reason to not sort: Hash keys are not required to
implement <=>. Now, we “know” that keys will be only Symbols but what
if not? You might see an exception from #sort. Comparing via Set
would be more robust here since we know that keys fulfill the
requirements for a Set element. So that would be

return false unless keys.to_set == other.keys.to_set

Kind regards

robert