Defining Singleton Methods
Ruby lets you define methods that are specific to a particular object. These are called singleton methods.
Here’s a simple string object and a regular, non-singleton method call:
| animal = "cat" |
| puts animal.upcase |
Produces:
| CAT |
This call results in the object structure shown in the following illustration:
The animal variable points to an object containing (among other things) the value of the string ("cat") and a pointer to the object’s class, String.
When we call animal.upcase, Ruby checks the object referenced by the animal variable and then looks up the method upcase in the class object referenced from the ...
Get Programming Ruby 3.3 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.