Reopening and monkey-patching singleton classes
suggest changeThere are three ways to reopen a singleton class:
- Call
class_evalon the singleton class. - Use a
class << objectblock. - Define a method directly on the object.
class Example
end
Example.singleton_class.class_eval do
def foo
:foo
end
end
Example.foo # => :foo
class Example
end
class << Example
def bar
:bar
end
end
Example.bar # => :bar
class Example
end
def Example.baz
:baz
end
Example.baz # => :baz
Every object has a singleton class:
class Example
end
first = Example.new
def first.foobar
:foobar
end
first.foobar # => :foobar
second = Example.new
# second.foobar raises NoMethodError
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents