class << self idiom in Ruby

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

What does class << self do in Ruby?

6条回答
  •  天涯浪人
    2020-11-22 14:07

    А singleton method is a method that is defined only for a single object.

    Example:

    class SomeClass
      class << self
        def test
        end
      end
    end
    
    test_obj = SomeClass.new
    
    def test_obj.test_2
    end
    
    class << test_obj
      def test_3
      end
    end
    
    puts "Singleton's methods of SomeClass"
    puts SomeClass.singleton_methods
    puts '------------------------------------------'
    puts "Singleton's methods of test_obj"
    puts test_obj.singleton_methods
    

    Singleton's methods of SomeClass

    test


    Singleton's methods of test_obj

    test_2

    test_3

提交回复
热议问题