How to remove a singleton method from within an instance method?

Is this possible?

I can easily define a singleton from
within an instance method, but I can’t
seem to get rid of it. See below.

Even calling private would be OK… but
I can’t figure that out either.

I’ll explain why I want to, if someone
can figure out how. :slight_smile:

Thanks,
Hal

class MyClass
def meth1
def self.foo; 123; end
end

def meth2
  # None of these works:
  # undef self.foo
  # remove_method :foo
  # Module.remove_method :foo
  # self.remove_method :foo
  # undef_method :foo
  # Module.undef_method :foo
  # self.undef_method :foo
  # self.instance_eval { undef :foo }
  # private :foo
  # Module.private :foo
  # self.private :foo
  # ... and various others
end

end

···


Hal Fulton
hal9000@hypermetrics.com

Is this possible?

svg% cat b.rb
#!/usr/bin/ruby
class MyClass
   def meth1
      def self.foo; 123; end
   end

   def meth2
      class << self; undef foo; end
   end
end
      
a = MyClass.new
a.meth1
p a.foo
a.meth2
p a.foo
svg%

svg% b.rb
123
./b.rb:16: undefined method `foo' for #<MyClass:0x40099d94> (NoMethodError)
svg%

Guy Decoux

“Hal E. Fulton” hal9000@hypermetrics.com wrote in

I can easily define a singleton from
within an instance method, but I can’t
seem to get rid of it. See below.

Even calling private would be OK… but
I can’t figure that out either.

Besides Guys solution I’d probably would do this

class MyClass
def get_ride_of_me(sym)
class << self; self end.\ # overcome remove beign private …
send(:remove_method,sym.to_s)
end

def add_me
def self.pingo
p “pingo”
end
end
end

t =MyClass.new
t.add_me
t.pingo # pingo
t.get_ride_of_me(:pingo)
t.pingo # no MethodError

I’ll explain why I want to, if someone
can figure out how. :slight_smile:

Okay we are waiting;-)

/Christoph