I know if I subclass the String class and override its capitalize method, I can call the String class' version of capitalize with super
. What if instead I reopened the String class and rewrote the capitalize method? Is there a way I can call the previous version of that method?
This is possible because Ruby supports a concept known as “Open classes”, which lets you do exactly this, i.e. extend an existing class, without altering the original class-block. “Monkey Patching” is something that's made possible thanks to the concept of open classes.
Override means two methods having same name but doing different tasks. It means that one of the methods overrides another method. If there is any method in the superclass and a method with the same name in its subclass, then by executing these methods, method of the corresponding class will be executed.
To override an inherited method, the method in the child class must have the same name, parameter list, and return type (or a subclass of the return type) as the parent method. Any method that is called must be defined within its own class or its superclass. You may see the @Override annotation above a method.
There are two standard approaches for defining class method in Ruby. The first one is the “def self. method” (let's call it Style #1), and the second one is the “class << self” (let's call it Style #2).
Not out of the box. A common approach is to rename the existing method to a new name. Then, in your rewritten version, call the old method by the new name.
def String
alias to_i old_to_i
def to_i
#add your own functionality here
old_to_i
end
end
You might also want to look at alias_method_chain
, which does some of this for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With