Recall you created a new method earlier (dynamic.rb) using send
to call define_method
and passed to it the name, m
, of the method to be created plus a block, &block
, containing the code of the new method:
dynamic.rb
def addMethod( m, &block ) self.class.send( :define_method, m , &block ) end
In addition to creating new methods, sometimes you may want to remove existing methods. You can do this using remove_method
within the scope of a given class. This removes the method specified by a symbol from a specific class:
rem_methods1.rb
puts( "hello".reverse ) #=> olleh class String remove_method( :reverse ) end puts( "hello".reverse ) #=> undefined method error!
If a method with the same name is defined for an ancestor of that class, the ancestor class method is not removed:
rem_methods2.rb
class Y def somemethod puts("Y's somemethod") end end class Z < Y def somemethod puts("Z's somemethod") end end zob = Z.new zob.somemethod #=> Z's somemethod class Z remove_method( :somemethod ) # Remove somemethod from Z class end zob.somemethod #=> Y's somemethod
In this example, somemethod
is removed from the Z class, so when zob.somemethod
is subsequently called on a Z object, Ruby executes the first method with that name in the ancestor classes of Z. Here, Y is the ancestor of Z, so its somemethod
method is used.
The undef_method
, by contrast, prevents the specified class from responding to a method call even if a method with the same name is defined in one of its ancestors. The following example uses the same Y and Z classes used in the previous example. The only difference is that this time somemethod
is undefined using undef_method
rather than merely removed from the current class using remove_method
:
undef_methods.rb
zob = Z.new zob.somemethod #=> Z's somemethod class Z undef_method( :somemethod ) #=> undefine somemethod end zob.somemethod #=> undefined method error
3.147.67.16