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, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.