Operators Are Methods

Operators are methods too.

We'll cover the following

As briefly mentioned earlier, a number has methods named like the arithmetic operators, +, -, *, and /.

It’s intuitive when considering that if everything is an object, then numbers are objects too. If doing things means operating with methods by way of calling them, then what would + be? A method.

If we call methods on objects using the dot (.) notation, then where are the dots in 2 + 3 * 4?

Ruby adds them for us. Take a look at the following code:

Press + to interact
puts number = 2 + 3 * 4

Ruby translates it to the following:

Press + to interact
puts number = 2.+(3.*(4))

These operators are all methods on numbers, and they can be called just like any other method. The same is true for lots of other operators, as we can see if we run 1.methods.sort. The code above is valid Ruby code, and both lines do exactly the same thing.

Syntax sugar

Ruby adds a little bit of syntax to make it easier to read and write for us. It allows us to write number = 2 + 3 * 4 instead of number = 2.+(3.*(4)), which is very cumbersome.

This is called syntax sugar because it makes the language more sweet (no kidding).

This works the same way for other things too.

For example, we’ve learned about the array and hash syntax that uses square brackets ([]) for reading and writing.

Ruby takes this code:

Press + to interact
array = [1, 2, 3]
array[3] = 4
puts array[3]
hash = { :one => 'eins', :two => 'zwei' }
hash[:three] = 'drei'
puts hash[:three]

And translates it to these method calls:

Press + to interact
array = [1, 2, 3]
array.[]=(3, 4)
puts(array.[](3))
hash = { :one => 'eins', :two => 'zwei' }
hash.[]=(:three, 'drei')
puts(hash.[](:three))

Knowing this can be helpful when you want to write classes that look and feel similar to arrays or hashes but behave differently.