Reopening and monkey-patching singleton classes

suggest change

There are three ways to reopen a singleton class:

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents