class << self idiom in Ruby

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

What does class << self do in Ruby?

6条回答
  •  -上瘾入骨i
    2020-11-22 14:14

    I found a super simple explanation about class << self , Eigenclass and different type of methods.

    In Ruby, there are three types of methods that can be applied to a class:

    1. Instance methods
    2. Singleton methods
    3. Class methods

    Instance methods and class methods are almost similar to their homonymous in other programming languages.

    class Foo  
      def an_instance_method  
        puts "I am an instance method"  
      end  
      def self.a_class_method  
        puts "I am a class method"  
      end  
    end
    
    foo = Foo.new
    
    def foo.a_singleton_method
      puts "I am a singletone method"
    end
    

    Another way of accessing an Eigenclass(which includes singleton methods) is with the following syntax (class <<):

    foo = Foo.new
    
    class << foo
      def a_singleton_method
        puts "I am a singleton method"
      end
    end
    

    now you can define a singleton method for self which is the class Foo itself in this context:

    class Foo
      class << self
        def a_singleton_and_class_method
          puts "I am a singleton method for self and a class method for Foo"
        end
      end
    end
    

提交回复
热议问题