Does operator overriding exist in Ruby?

Have you ever wondered if there is any concept of operator overriding in ruby?

In my previous article 3 Pillars of Ruby, I have mentioned that everything in Ruby is an object and every operation is a method call on an object.

So, the answer is yes because every operator in ruby is a method defined on an object and you can easily override an existing method in ruby as all classes in ruby are open classes.

Let’s take an example:

irb(main):001:0> 1 + 2
=> 3
irb(main):002:0> 'a' + 'b'
=> "ab"
irb(main):003:0> ['a'] + ['b']
=> ["a", "b"]

As you can see + operator is performing addition on 3 different types of objects (remember even data types are objects in ruby)

Let’s try to understand what exactly is happening here by re-writing above statements to:

irb(main):006:0> 1 + 2
=> 3
irb(main):007:0> 1.+(2)
=> 3
irb(main):008:0> ‘a’ + ‘b’
=> "ab"
irb(main):009:0> ‘a’.+(‘b’)
=> "ab"
irb(main):010:0> ['a'] + ['b']
=> ["a", "b"]
irb(main):011:0> ['a'].+(['b'])
=> ["a", "b"]

As, you can see, I am using Dot notation of calling a method in above statements, that means + is just a method defined on different type of objects as follows:

Fixnum#+, String#+, Array#+

So, can I write my own + method?

Yes, you can and that’s what we call operator overriding 🙂

Let’s take an example by modify the + operator of Numeric class to perform subtraction. 😛

irb(main):001:0> class Fixnum
irb(main):002:1> def +(n)
irb(main):003:2> self - n
irb(main):004:2> end
irb(main):005:1> end
=> :+
irb(main):006:0> 5 + 5
=> 0

You can do that same trick with any operator like + x % etc.

If you like this article, you may be interested in reading my other articles on

Ruby Memoization using Singleton Method &

3 Pillars of Ruby

Suggestions and feedbacks are most welcome 😃