Ruby 1.9.2
標準クラス・モジュール > Object > singleton_class
obj.singleton_class
singleton_classメソッドは、オブジェクトの特異クラスを返します。
小さい整数(Fixnum)およびシンボルに対してsingleton_classを呼び出すと、例外TypeErrorが発生します。true、false、nilに対して呼び出すと、特異クラスではなくTrueClass、FalseClass、NilClassを返します。
次の例では、オブジェクトcatの特異クラスをsingletonに取り出し、define_methodで特異メソッドを定義しています。
class Cat
end
cat = Cat.new
singleton = cat.singleton_class
singleton.send(:define_method, :hello) { "meow!" }
puts cat.hello
meow!
1.9.2より前のバージョンで特異クラスを取り出すには、次のようにclass << obj; self endの戻り値を使います。
singleton = class << cat; self end
class : オブジェクトのクラスを返す。