重新打开(猴子修补)Singleton 类
有三种方法可以重新打开 Singleton 类
- 在单例类上使用 class_eval。
- 使用 class <<块。
- 使用 def直接在对象的 singleton 类上定义一个方法
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
每个对象都有一个可以访问的单例类
class Example
end
ex1 = Example.new
def ex1.foobar
  :foobar
end
ex1.foobar #=> :foobar
ex2 = Example.new
ex2.foobar #=> NoMethodError