Search code examples
ruby

Remove a method only from an instance


Is it possible to remove a method from a single instance?

class Foo
  def a_method
    "a method was invoked"
  end
end

f1 = Foo.new
puts f1.a_method # => a method was invoked

I can remove a_method from the class an from the already created object with this:

class Foo
  remove_method(:a_method)
end

If I invoke a_method from the same object:

puts f1.a_method # => undefined method

If I create another object:

f2 = Foo.new
puts f2.a_method # => undefined method

How can I only remove a method from an specific single object?


Solution

  • Yes, it is possible:

    f1.instance_eval('undef :a_method')