How can I create a class with no instance methods defined? Not even __send__
or __id__
.
You can use Module# undef_method
to undefine methods:
class Foo < BasicObject
instance_methods.each { |method| undef_method(method) }
end
Foo.instance_methods #=> []
foo = Foo.new
foo.__id__ #=> NoMethodError: undefined method `__id__' for #<Foo:0x007fb9da565dd8>
foo.__send__(:test) #=> NoMethodError: undefined method `__send__' for #<Foo:0x007fb9da565dd8>
In this example Foo
inherits from BasicObject
, because this class itself has very few instance methods defined and thus, undefining them is faster. This is not obligatory, meaning, that you can undefine instance methods from any class no matter what it inherits from, so it could be very well written as:
class Foo
instance_methods.each { |method| undef_method(method) }
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.