15 janeiro 2014

Ruby: remove_method vs undef_method

When you use "remove_method", it will remove only the method from the object that "remove_method" method was called. If there's a method with the same name of the removed one in the superclass, it will be called.
class Person
  def talk
    "what is up?"
  end
end

Person.class_eval { remove_method :talk }
Person.new.respond_to(:talk)? #=> false

class Kid < Person
  def talk
    "mommy"
  end
end

Kid.new.talk #=> mommy
Kid.class_eval { remove_method :talk }
Kid.new.talk #=> what is up ?
To avoid that, use undef_method:
Kid.class_eval { undef_method :talk }
Kid.new.talk #=> NoMethodError
Also, remove_method and undef_method are private, that's why you have to use "eval".