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

Get The Book of Ruby 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.