undef_method vs remove_method
Ruby's undef_method
and remove_method
are both methods for removing a method from a class, but there are subtle differences between the two.
Say we have two classes that both define the method name
, with one class inheriting from the other:
class Human
def name
"homo sapien"
end
end
class Child < Human
def name
"small homo sapien"
end
end
remove_method
fully deletes a method from a particular class, but will still look for the method on parent classes or modules when called on the particular class:
child = Child.new
child.name
# => "small homo sapien"
class Child
remove_method :name
end
child.name
# => "homo sapien"
undef_method
in contrast will prevent Ruby from looking up the method on parent classes
child = Child.new
child.name
# => "small homo sapien"
class Child
undef_method :name
end
child.name
# => raises NoMethodError
# undefined method `name' for #<Child:0x00007ffd91a007a8>
Tweet