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?

- 8,294
- 12
- 65
- 108
-
This is a duplicate of [When monkey patching a method, can you call the overridden method from the new implementation](http://StackOverflow.Com/q/4470108/). – Jörg W Mittag Jun 10 '11 at 16:20
2 Answers
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.

- 91,582
- 23
- 169
- 153

- 50,258
- 9
- 107
- 126
There is also another interesting approach to get super
working - if the class to open supports it (e.g. because it's written by yourself):
The methods of the class are not directly defined in the class body, but in another module that is then included. To overwrite a method of the re-opened class, include your own module with the extend version of it (which might use super
).
This is, for example, used in the irb-alternative ripl to let plugins implement their own versions of core methods (which call super
to get the original behaviour).

- 9,079
- 2
- 40
- 37