Skip to the workspace
Pebellslearn by building
Operators  ›  Lesson

Comparison Operators

Comparison 12 minRuby comparison methods define value equality, hash-key equality, identity or ordering. Their exact behavior depends on the class; <=> can return nil when values are not comparable.

ruby / Comparison Operators

Explore each scene at your own pace.

01 · The rule

The rule

Comparison Operators

Ruby comparison methods define value equality, hash-key equality, identity or ordering. Their exact behavior depends on the class; <=> can return nil when values are not comparable.

Compare value equality, identity and ordering according to the object's contract.

Bean Cart gives a loyalty stamp when an order is at least 5.00. The check total >= 5 looks trivial, but Ruby has several ideas of "equal", and one surprising operator, <=>, that powers every sort you will ever run.

The rule

== compares values, equal? compares identity, <=> answers minus one, zero or one.

The everyday operators all return true or false:

total = 5.0
total == 5      # => true   (equal value; 5 and 5.0 count as equal)
total != 4.5    # => true   (not equal)
total > 4.5     # => true
total >= 5      # => true
"tea" < "tub"   # => true   (strings compare letter by letter)

Strings compare character by character by their character codes, and every capital letter comes before every lowercase one, so "Zebra" < "apple" is true.

For stricter questions, Ruby offers methods:

1 == 1.0          # => true   same value
1.eql?(1.0)       # => false  same value AND same type? No
a = "latte"
b = "latte"
a == b            # => true   same content
a.equal?(b)       # => false  not the very same object
a.equal?(a)       # => true

The spaceship operator <=> compares two values and returns -1 if the left is smaller, 0 if they are equal, and 1 if the left is bigger. It returns nil when the two cannot be compared:

4.5 <=> 5.0     # => -1
5 <=> 5         # => 0
"mocha" <=> "latte"  # => 1
5 <=> "five"    # => nil

Sorting uses <=> behind the scenes. If you define <=> in your own class, Ruby can sort your objects.

There is also ===, the case-equality operator. It reads best as "does the right side belong to the left?": Integer === 5 is true and (1..10) === 7 is true. You rarely write it yourself, but case statements use it, as you will see later.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.