On Sun, Apr 17, 2011 at 5:37 PM, Su Zhang <zhangsu / live.com> wrote:

> Hello,
>
> According to the book Programming Ruby by Dave Thomas, "an
> undened method still exists - it is simply marked as being undened."
> Why is it not completely removed?
>
> I find this somewhat related to the fact that an object still cannot be
> dumped after "undefing" its singleton methods.
>
> obj = Object.new
>
> def obj.foo
> end
>
> p obj.respond_to? :foo  # => true
>
> class << obj
>  undef foo
> end
>
> p obj.respond_to? :foo  # => true
>
> Marshal.dump(obj)       # => error
>
> --
> Posted via http://www.ruby-forum.com/.
>


I assume because the intuition is that undefining a method on an object
means the object should raise the undefined error when you try to call it.
But simply removing it would not prevent Ruby from finding an inherited
version of the method.

ie

o = Object.new

o.to_s  # => "#<Object:0x0000010086a460>"

def o.to_s
  "o#to_s"
end

o.to_s # => "o#to_s"

class << o
  remove_method :to_s
end

o.to_s    # => "#<Object:0x0000010086a460>"



It still has a to_s method, because it inherits one from Object. What if you
want it to not respond to that one? You can't undefine the method on object,
or every object loses it's inherited to_s method. So you need to interrupt
dispatch when this method is called. Hence undef simply raises the same
error you would have gotten if it hadn't found the method:


o = Object.new

o.to_s  # => "#<Object:0x0000010086a488>"

def o.to_s
  "o#to_s"
end

o.to_s # => "o#to_s"

class << o
  undef :to_s
end

o.to_s    # =>
# ~> -:15:in `<main>': undefined method `to_s' for
#<Object:0x0000010086a488> (NoMethodError)