7.2. Recurrent syntactic sugar

As you know, Ruby sometimes lets you use sugary notation in place of the usual object.method(args) method-calling syntax. This lets you do nice-looking things, such as using a plus sign between two numbers, like an operator

x = 1 + 2

instead of the odd-looking method-style equivalent:

x = 1.+(2)

As you delve more deeply into Ruby and its built-in methods, be aware that certain methods always get this treatment. The consequence is that you can define how your objects behave in code like this

my_object + my_other_object

simply by defining the + method. You’ve seen this process at work, particularly in connection with case equality and defining the === method. But now let’s look more extensively at this elegant technique. ...

Get The Well-Grounded Rubyist, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.