Check if two hashes have the same set of keys

hash, ruby

Solution

Try:

# Check that both hash have the same number of entries first before anything
if h1.size == h2.size
    # breaks from iteration and returns 'false' as soon as there is a mismatched key
    # otherwise returns true
    h1.keys.all?{ |key| !!h2[key] }
end

Enumerable#all?

worse case scenario, you'd only be iterating through the keys once.

Problem

What is the most efficient way to check if two hashes `h1` and `h2` have the same set of keys disregarding the order? Could it be made faster or more concise with close efficiency than the answer that I post?

Original source