def sum(x,y); x+y; end # Define a method puts sum(1,2) # Use it undef sum # And undefine it
In this code, the def
statement defines a global method, and undef
undefines it. undef
also works within classes to undefine the instance methods of the class. Interestingly, undef
can be used to undefine inherited methods, without affecting the definition of the method in the class from which it is inherited. Suppose class A
defines a method m
, and class B
is a subclass of A
and therefore inherits m
. If you don't want to allow instances of class B
to be able to invoke m
, you can use undef
m
within the body of the subclass.
undef
is not a commonly used statement. In practice, it is much more common to redefine a method with a new def
statement than it is to undefine or delete the method.
Note that the undef
statement must be followed by a single identifier that specifies the method name. It cannot be used to undefine a singleton method in the way that def
can be used to define such a method.
Within a class or module, you can also use undef_method
(a private method of Module) to undefine methods. Pass a symbol representing the name of the method to be undefined.
Casiano Rodriguez León 2015-01-07