compare_by_identity

1047 views

What's the return value of the following Ruby code?

h = {}.compare_by_identity

h["key"] = 42
h["key"] = 84

h # => ???

The correct answer is

It raises KeyError

{ "key" => 42 }

{ "key" => 84 }

{ "key" => 42, "key" => 84 }

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

Explanation

In the provided code snippet, {} initializes an empty hash.

However, when compare_by_identity is called on this hash object, it changes the behavior of how keys are compared.

Instead of comparing keys by their content, keys are compared by their object identity

# Enable comparing keys by object identity
h = {}.compare_by_identity

Subsequently, two values are assigned to the key "key".

Normally, in a regular hash, the second assignment would overwrite the first one, leading to only one entry for "key" with the latest assigned value.

However, because the hash now compares keys by identity, even though both assignments use the same key ("key"), they are treated as distinct keys due to having different object identities

# Assign values to the key "key"
h["key"] = 42
h["key"] = 84

As a result, the hash h contains both entries associated with the key "key", each with its respective value:

puts h # => {"key"=>42, "key"=>84}

This demonstrates that when compare_by_identity is used, similar keys can exist in the same hash as long as their identities are different.

Voilà!

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

RubyCademy ©