特異クラス概要
インスタンスに適用される特別なクラス。シングルトンクラスともいう。
インタプリタ内部だけで使用するクラスでユーザ側には意識させたくないクラス
特異クラス定義
class << で特定オブジェクトの特異クラスを定義できる。クラスメソッド定義で使うやつ。
class << オブジェクト名(クラス名とかインスタンス名とか)
end
特異クラス参照
selfを使う
class C
end
c = C.new
singleton_class = class << c
self
end
singleton_class
=> #<Class:#<C:0x00007fd30219e998>>
singleton_class
class C
end
c = C.new
c.singleton_class
=> #<Class:#<C:0x00007fd30219e998>>
特異メソッド概要
特定のインスタンスに定義できるメソッド。
特異メソッド定義
インスタンス名.メソッド名
class C
end
c = C.new
def c.c_method
p 'cの特異メソッドだよ'
end
c.c_method
=> "cの特異メソッドだよ"
class << オブジェクト名 内で定義
class C
end
c = C.new
class << c
def c_method
p 'cの特異メソッドだよ'
end
end
c.c_method
=> "cの特異メソッドだよ"
class << オブジェクト名 内でinclude
module M
def m_method
p 'Mのメソッドだよ'
end
end
class C
end
c = C.new
class << c
include M
end
c.m_method
=> "Mのメソッドだよ"
extend
module M
def m_method
p 'Mのメソッドだよ'
end
end
class C
end
c = C.new
c.extend(M)
c.m_method
=> "Mのメソッドだよ"
instance_eval
class C
end
c = C.new
c.instance_eval do
def c_method
p "cの特異メソッドだよ"
end
end
c.c_method
=> "cの特異メソッドだよ"
0 件のコメント:
コメントを投稿