Ruby Language Reopening (monkey patching) Singleton Classes


Example

There are three ways to reopen a Singleton Class

  • Using class_eval on a singleton class.
  • Using class << block.
  • Using def to define a method on the object's singleton class directly
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 which you can access

class Example
end
ex1 = Example.new
def ex1.foobar
  :foobar
end
ex1.foobar #=> :foobar

ex2 = Example.new
ex2.foobar #=> NoMethodError