Overriding Methods
Sometimes you may want to redefine a method that already exists in some class. You’ve done this before when, for example, you created classes with their own to_s methods to return a string representation. Every Ruby class, from Object downward, has a to_s method. The to_s method of the Object class returns the class name and a hexadecimal representation of the object’s unique identifier. However, many Ruby classes have their own special versions of to_s. For example, Array.to_s concatenates and returns the values in the array.
When a method in one class replaces a method of the same name in an ancestor class, it is said to override that method. You can override methods that are defined in the standard class library such as
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access