Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a method only from an instance

Tags:

ruby

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?

like image 789
hector Avatar asked Nov 23 '14 22:11

hector


1 Answers

Yes, it is possible:

f1.instance_eval('undef :a_method')
like image 195
Agis Avatar answered Oct 16 '22 15:10

Agis