5

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?

Kvass
  • 8,004
  • 10
  • 62
  • 104
  • 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 Answers2

6

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.

Daniel Vandersluis
  • 87,806
  • 20
  • 161
  • 152
Jacob Mattison
  • 48,909
  • 9
  • 107
  • 125
0

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).

J-_-L
  • 8,991
  • 2
  • 39
  • 37