使用带self的类内方法调用Ruby类方法和不带self的类内方法调用Ruby类方法有什么区别吗?

使用带self的类内方法调用Ruby类方法和不带self的类内方法调用Ruby类方法有什么区别吗?,ruby,Ruby,我有点好奇地想知道,下面两种方法之间有什么区别吗 使用self使用类内方法调用类方法 class Test def self.foo puts 'Welcome to ruby' end def self.bar self.foo end end Test.bar#欢迎来到ruby 使用类内方法调用类方法而不使用self class Test def self.foo puts 'Welcome to ruby' end def self.bar

我有点好奇地想知道,下面两种方法之间有什么区别吗

  • 使用self使用类内方法调用类方法

    class Test
      def self.foo
       puts 'Welcome to ruby'
      end
    
     def self.bar
      self.foo
     end
    
    end
    
    Test.bar
    #欢迎来到ruby

  • 使用类内方法调用类方法而不使用self

    class Test
      def self.foo
       puts 'Welcome to ruby'
      end
    
     def self.bar
      foo
     end
    
    end
    
    Test.bar
    #欢迎来到ruby


  • 是的,有区别。但不是在你的例子中。但是如果
    foo
    是一个
    private
    类方法,那么您的第一个版本将引发一个异常,因为您使用显式接收器调用
    foo

    class Test
      def self.foo
        puts 'Welcome to ruby'
      end
      private_class_method :foo
    
      def self.bar
        self.foo
      end
    end
    
    Test.bar
    #=> NoMethodError: private method `foo' called for Test:Class
    
    但第二个版本仍然有效:

    class Test
      def self.foo
        puts 'Welcome to ruby'
      end
      private_class_method :foo
    
      def self.bar
        foo
      end
    end
    
    Test.bar
    #=> "Welcome to ruby"
    

    另一个区别是:如果有一个局部变量
    foo
    foo
    将引用该变量,
    self.foo
    将引用该方法。请注意,这并不特定于类方法,调用实例方法也是一样的。