Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 134 ยท Object-Oriented Ruby

Operator Overloading

Learn how Ruby operators are just method calls, and how to define +, -, ==, <=>, [], <<, unary operators, coerce and to_proc so your own classes feel built in.

In Ruby, 3 + 4 is not special syntax handled by the compiler. It is a method call: 3.+(4). The same is true of ==, <<, [], ! and most other operators. That means you can give your own classes operators simply by defining methods with those names. A Money can be added, a Vector scaled, a Matrix indexed with m[1, 2], and a Playlist extended with <<.

This is powerful, and also easy to abuse. This lesson shows which operators you can define, how to do it correctly (including the tricky coerce protocol that makes 3 * vector work), and the design rules that keep operator overloading helpful rather than confusing. It follows naturally from Equality and Identity and The Ruby Object Model.

Operators are methods

You can call an operator with ordinary method syntax to prove it:

Ruby Operators are method calls

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.

Ruby simply turns the operator into a method call on the left-hand object, so which method runs depends on that object's class. Operators that look like they combine two values always ask the left object to do the work, a point that matters for coerce later.

A first operator: adding vectors

Define the operator as an ordinary instance method. The single argument is the right-hand operand.

Ruby A Vec class with arithmetic

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.

Notice a += b: Ruby rewrites it to a = a + b, so you get += for free, and the same is true for -=, *=, <<= and the rest. Assignment operators and &&= / ||= are not methods and cannot be overloaded, but the arithmetic inside them is.

The failing call is instructive. a + 1 evaluates 1.x inside Vec#+, and since 1 has no x, you get a NoMethodError about x on an Integer, not a friendly message about vectors. Production code usually checks its argument and raises a clear error (shown in a later example).

The full operator menu

These are the operators you can define as methods:

Group Operators Notes
Arithmetic + - * / % ** Binary: one argument
Bitwise & | ^ << >> << is also the "append" convention
Comparison == < <= > >= <=> === <, <= etc. come from Comparable
Match =~ !~ !~ is derived from =~
Indexing [] []= Any number of arguments
Unary +@ -@ ~ ! Defined with the @ suffix for + and -
Call .() Calls the method named call

You cannot overload &&, ||, and, or, not, defined?, = and ..: they are handled by the language itself. != is automatically the negation of ==, and !~ the negation of =~.

Unary operators and indexing

Unary plus and minus use the suffix @ to tell them apart from the binary forms. Indexing takes whatever arguments you want, including several (a matrix) or ranges.

Ruby Unary operators and indexing

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.

Two things to remember. The return value of []= is ignored by an assignment expression (g[1, 0] = "#" evaluates to the assigned value "#", whatever the method returns), so do not rely on it. And ! is rarely worth overloading, because in Ruby only nil and false are falsy and truthiness tests (if v) never call !.

Equality and ordering

Define == to give value semantics, and <=> plus include Comparable to get <, <=, >, >=, between? and clamp for free. The rules for correct equality (eql? and hash, so your objects work as hash keys) are in Equality and Identity; ordering is covered in Comparable.

Ruby Equality and ordering with Comparable

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.

When <=> returns nil (no sensible ordering), < raises ArgumentError with a message such as comparison of Money with 5 failed, while == just returns false. That asymmetry is by design: you may always ask "are these equal?" but not always "which is bigger?".

Appending with <<

<< is the conventional "append" operator, used by Array, String, Set and IO. Return self so that calls can be chained:

Ruby A chainable append operator

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.

Forgetting to return self is the classic bug: list << "a" << "b" would then call << on whatever the first call returned.

Mixed types and coerce

So far Vec * 3 works, but 3 * Vec does not, because 3.*(vec) asks Integer#* to multiply by a Vec, which it does not understand. Ruby gives Integer a way out: it calls vec.coerce(3) and expects an array [a, b] of two values it can combine with the original operator. If you return [Vec-like left, self], Ruby computes left * self for you.

Ruby 3 * vec fails, then coerce fixes it (fails on purpose)

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 stops with Vec can't be coerced into Integer (TypeError). Add coerce, and numbers on the left work:

Ruby Teaching a number how to multiply a Vec

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.

When Integer#* receives something that is not a number, it calls v.coerce(3). We return a tiny Scaler and v; Ruby then evaluates scaler * v, which delegates to v * 3. For a class with a proper numeric tower (like Rational or BigDecimal), coerce instead converts the number into your type and returns [Money.new(number), self]. Note the explicit TypeError: a clear message beats an accidental NoMethodError.

Calling objects and converting to procs

Two more "operators" make objects behave like functions:

  • obj.(args) is shorthand for obj.call(args). Any object with a call method works with it.
  • &obj passes an object where a block is expected. Ruby calls obj.to_proc to convert it, which is how map(&:upcase) works (Symbol#to_proc).
Ruby call, .() and to_proc

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.

Defining to_proc on a class (as Even.to_proc above) lets you hand the class itself to select. This pattern is common for small "specification" objects and for composing validation rules.

Rules for good operator overloading

  1. Mean what readers expect. + should be addition-like, << should append, [] should look something up. A Money + Money is natural; User + Role is not.
  2. Return a new object from arithmetic operators, like numbers and strings do. Mutating self in + surprises callers; reserve mutation for << and []=.
  3. Validate the argument and raise a clear TypeError or ArgumentError, rather than leaking a NoMethodError from the middle of your method.
  4. Keep the set consistent. If you define ==, define hash and eql? too if the object can be a hash key. If you define <=>, include Comparable.
  5. Prefer named methods when the operation has no obvious symbol. order.apply_discount(10) beats order % 10.

Overloading is global to the class, and Ruby lets anyone reopen a core class and redefine + on Integer. Do not do that in application code; see Monkey Patching and Safe Alternatives.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the expression a + b actually do in Ruby?

    Operators are method calls on the left operand: a + b is a.+(b). That is why you can define them in your own classes.
  2. 2. How do you define the unary minus operator (-obj) in a class?

    Unary plus and minus use the @ suffix (+@ and -@) to distinguish them from the binary operators.
  3. 3. Which method must you define to get <, >, between? and clamp by including Comparable?

    Comparable builds all the other comparison methods on top of <=>.
  4. 4. Why does 3 * vec fail even though vec * 3 works?

    The left operand does the work. Integer#* asks the right operand's coerce to produce two values it can combine. Without coerce it raises TypeError.
  5. 5. Which of these operators can NOT be overloaded?

    &&, ||, and, or, not and = are part of the language and cannot be redefined. The others are ordinary methods.

Summary

  • Operators like +, ==, << and [] are ordinary methods called on the left operand, so you define them with def.
  • a += b is a = a + b; != and !~ are derived. &&, ||, not and = cannot be overloaded.
  • Use -@ and +@ for unary operators, and [] / []= for indexing with any number of arguments.
  • Define <=> and include Comparable for ordering; return self from << so calls can chain.
  • Implement coerce so a number on the left side can work with your type, and call / to_proc for function-like objects.
  • Overload only when the meaning is obvious, return new objects, and validate arguments.

Next: Copying Objects