Markus Orrelly
Markus Orrelly

Reputation: 1689

Ruby - How to remove a setter on an object

Given a class like this:

class B
    class << self
        attr_accessor :var
    end
end

Suppose I can't modify the original source code of class B. How might I go about removing the setter on the class variable var? I've tried using something like B.send("unset_method", "var="), but that doesn't work (nor does remove_method, or overwriting that method with a var= method that doesn't do anything). Any ideas?

Upvotes: 0

Views: 508

Answers (2)

Brian Takita
Brian Takita

Reputation: 1655

Try:

class B
  class << self
    undef var=
  end
end

You may want to use remove_method instead:

class B
  class << self
    remove_method :var=
  end
end

To see the differences, go to: http://www.nach-vorne.de/2008/2/28/undef_method-remove_method/

Upvotes: 1

Mark Rendle
Mark Rendle

Reputation: 9414

class <<B ; remove_method :var= ; end

Upvotes: 0

Related Questions