OLW: Testing Hash Equality

Another #rubyoneliner this week. We use this to test hash equality for cases where we don’t care about the order of elements in an array for either keys or values.

class Hash
def hash_rep
sort.map{|k,v| Hash[(k.is_? Array ? k.sort : (k.is_a? Hash ? k.hash_rep : k)) => v.is_a? Array ? v.sort : (v.is_a? Hash ? v.hash_rep : v)]}
end
end

We have opened up the Hash class to create a method that sorts the arrays at any level in a potentially deeply nested hash. You can use it to test hash equality by comparing the representations generated as follows:
h1.hash_rep == h2.hash_rep

“I never wanted to believe that my Dad was stealing from his job as a road worker. But when I got home, all the signs were there.”

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s