class << self idiom in Ruby

后端 未结 6 1580
时光说笑
时光说笑 2020-11-22 13:51

What does class << self do in Ruby?

6条回答
  •  萌比男神i
    2020-11-22 13:59

    What class << thing does:

    class Hi
      self #=> Hi
      class << self #same as 'class << Hi'
        self #=> #
        self == Hi.singleton_class #=> true
      end
    end
    

    [it makes self == thing.singleton_class in the context of its block].


    What is thing.singleton_class?

    hi = String.new
    def hi.a
    end
    
    hi.class.instance_methods.include? :a #=> false
    hi.singleton_class.instance_methods.include? :a #=> true
    

    hi object inherits its #methods from its #singleton_class.instance_methods and then from its #class.instance_methods.
    Here we gave hi's singleton class instance method :a. It could have been done with class << hi instead.
    hi's #singleton_class has all instance methods hi's #class has, and possibly some more (:a here).

    [instance methods of thing's #class and #singleton_class can be applied directly to thing. when ruby sees thing.a, it first looks for :a method definition in thing.singleton_class.instance_methods and then in thing.class.instance_methods]


    By the way - they call object's singleton class == metaclass == eigenclass.

提交回复
热议问题