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 to_s
as well as methods defined in your own classes. If you need to add new behavior to an existing method, remember to call the superclass’s method using the super
keyword at the start of the overridden method.
Here is an example:
override.rb
class MyClass def sayHello return "Hello from MyClass" end def sayGoodbye return "Goodbye from MyClass" end end class MyOtherClass < MyClass def sayHello #overrides (and replaces) MyClass.sayHello return "Hello from MyOtherClass" end # overrides MyClass.sayGoodbye but first calls that method # with super. So this version "adds to" MyClass.sayGoodbye def sayGoodbye return super << " and also from MyOtherClass" end # overrides default to_s method def to_s return "I am an instance of the #{self.class} class" end end
18.216.27.251