Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 134 ยท Object-Oriented Ruby

Equality and Identity

Learn the four kinds of equality in Ruby - ==, eql?, equal? and === - how hash keys use eql? and hash, and how to write correct custom equality for your own classes.

"Are these two things the same?" sounds like a simple question, but programs mean several different things by it. Are they the same object in memory? Do they hold the same value? Would they be treated as the same key in a hash? Does one match the other in a case statement? Ruby gives each question its own method: equal?, ==, eql? and ===. Mixing them up is a classic source of bugs, particularly with hash keys and custom classes.

This lesson explains the four methods with runnable proof, shows how Hash and uniq decide that two objects are the same key, and walks through the correct way to define equality for your own classes so that they behave in sets, hashes and comparisons.

Identity: equal?

equal? asks the strictest question: are these two variables the same object? Every object has a unique id, and equal? compares them. You should never override it.

Ruby Identity with equal? and object_id

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

a and b hold equal text but are two separate string objects, so == is true and equal? is false. c is just another name for the object a points to. Small integers, symbols, nil, true and false exist only once, so equal? is true for them. A very large integer such as 2**70 is a new object each time, so == says true but equal? says false. The lesson: use equal? only when you truly care about object identity, for example to detect a cycle or a sentinel value.

Value equality: ==

== is the everyday equality operator. Its default implementation in Object is the same as equal?, but nearly every core class overrides it to compare content: strings by characters, arrays element by element, hashes by key/value pairs.

Ruby == compares content, and converts between numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Hash equality ignores insertion order. Array equality compares element by element with ==, so 2 and 3.0 do not matter as long as == holds for each pair of elements (here 2 == 2 and 3 == 3.0). 1 == 1.0 is true because numeric == converts across types. A string and a symbol are never equal. A plain object, as in Plain.new == Plain.new, is false because the inherited == falls back to identity. The inequality operator != is automatically the negation of ==, so you never define it yourself.

Hash-key equality: eql? and hash

A Hash needs to find a key fast. It does this in two steps: it calls hash on the key to get an integer and finds the bucket, then compares the candidates with eql?. So two objects are the same hash key only if a.eql?(b) and a.hash == b.hash. Set, uniq, group_by, tally, -, & and | on arrays all use this same pair.

eql? is stricter than ==: it does not convert types.

Ruby == versus eql? and hash keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Although 1 == 1.0 is true, 1.eql?(1.0) is false, so a hash with the key 1 does not answer for 1.0 (the lookup returns nil), uniq keeps both numbers, and the set holds three elements. When you need "equal by ==" semantics for grouping, normalise the values first, as the uniq { it.to_i } form does. (Set is built in since Ruby 3.5 and 4.0, so the require is harmless but optional.)

=== : the case equality operator

=== has the same family resemblance, but a different purpose: it answers "does this value belong to that pattern?". It is what case/when calls (when X runs X === value), and what grep and Array#any?(pattern) use. The receiver is the pattern, so order matters.

Ruby === for ranges, classes, regexes and lambdas

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

(1..10) === 5 is true, but 5 === (1..10) is false because Integer#=== is plain equality and a number is not a range. For classes, Integer === 5 means "is 5 an Integer?", the opposite of reading it left to right. In the case, the string "42" reaches the regex branch before String because when clauses run in order. By default === of other objects calls ==, so you rarely define it unless you build a pattern-like class. More on case is in case and when.

Defining equality for your own class

The default == is identity, which is rarely what you want for value-like objects such as a point, a money amount or a version number. To make them behave, define ==, eql? and hash together, based on the same fields.

Ruby A value class with ==, eql? and hash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

All three pieces work together. == compares the fields and rejects other types (a == 500 is false, not an exception). eql? is an alias of == here, which is right for value objects. hash delegates to an array of the same fields, because Array#hash already mixes the hashes of its elements well. The result: uniq collapses a and b, the hash finds b with the key a, and include? uses ==.

The contract is: if a.eql?(b) then a.hash == b.hash. If you override eql? and forget hash, equal objects usually land in different buckets and hash lookups silently fail. If you define hash from fields that can change, an object stored as a key becomes unreachable after mutation.

What goes wrong without hash

Ruby Overriding == but not hash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

This version defines == only. include? uses ==, so it finds b. But uniq and - use hash and eql?, so they treat the two tags as different: uniq.size is 2, the subtraction removes nothing (the result still has one element), and the hash lookup returns nil. Behavior that differs between include? and uniq is a sure sign that ==, eql? and hash disagree. Define all three or none.

Mutable keys: a trap

Because the bucket is chosen from hash at insertion time, changing a key later hides it from the hash. Strings used as keys are copied and frozen for exactly this reason; your own objects are not.

Ruby A mutated key gets lost

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

After box.size = 2 the entry is still in the table (size is 1) but neither lookup can find it, because it sits in the bucket for the old hash code. rehash rebuilds the table and repairs it. The last lines show that a String key is copied and frozen by the hash (true) while your original string stays unfrozen (false). The better habit is to use immutable objects as keys: freeze them, or use Data.define/Struct (Struct and Data), which come with correct ==, eql? and hash already.

Comparable gives you == for free

If your objects have a natural order, include Comparable and define <=>. You receive <, <=, >, >=, between?, clamp and also == (true when <=> returns 0). Comparable#== does not define eql? or hash, so add those if the objects go into hashes. The topic has its own lesson: Comparable.

Ruby Comparable supplies ==

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The last line prints false: Comparable gave us == but not eql?, so these versions would still be different hash keys.

Quick reference

Method Question it answers Default Used by
equal? Same object? identity you, rarely; never override
== Same value? identity (overridden by core classes) include?, index, !=
eql? Same value and same type, as a hash key? identity Hash, Set, uniq, -, &
hash Integer fingerprint, equal for eql? objects identity-based Hash, Set, uniq
=== Does the value match this pattern? == case/when, grep, any?(pattern)

Rules of thumb: write value classes with ==, eql? and hash from the same fields; prefer Data.define when you can; keep key objects immutable; and remember that === reads right to left.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Two strings hold the text "ruby". Which comparison is false?

    Separate string objects have different identities, so equal? is false. ==, eql? and === all compare content.
  2. 2. Why does { 1 => :a }[1.0] return nil?

    == converts between numeric types, but eql? does not, and hashes use eql?.
  3. 3. You override == in a class but not hash or eql?. What is the likely symptom?

    include? uses ==. uniq, Set and Hash use hash and eql?, which still use identity.
  4. 4. What does Integer === 5 mean in a case statement such as when Integer?

    === is the membership test. Class#=== returns true when the argument is an instance of the class.
  5. 5. What is the problem with using a mutable object as a hash key?

    The bucket was chosen from the old hash code. After mutation the key looks in a different bucket.

Summary

  • equal? tests object identity; do not override it.
  • == tests value equality and is the default for include? and !=.
  • eql? plus hash decide hash-key equality, and are used by Hash, Set, uniq, - and &.
  • === is the membership test behind case/when; the pattern goes on the left.
  • Define ==, eql? and hash together from the same fields, or use Data.define/Struct.
  • Keep hash keys immutable. Comparable supplies == from <=> but not eql? or hash.

Next: to_s, inspect and Conversions