class << Hoge; endのシンタックスについて
ruby 2.0.0p247
クラスメソッドを定義するやつ。
class << String def hello :hello end end
こういうものだと思ってたけどなんとなくわかった。
前提の知識として、クラスメソッドというのはClassオブジェクトの特異メソッドである。(class式で定義している定数の中はClassオブジェクトが入ってる)
特異メソッドが定義されている場所は、特異クラスである。
結論、
『class << 』式内でのselfは、Classオブジェクトの特異クラスとなっており、特異クラスに対してメソッドを定義していることになる。
class Hoge; end class << Hoge p self def _class_method1 :_class_method1 end end # 上と同じ A = Hoge.singleton_class class A def _class_method2 :class_method2 end end Hoge._class_method1 Hoge._class_method2
ややこしい。