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

时间:2021-05-03 22:27:47

I am little bit curious about to know that, is there any difference between below two approaches?

我有点好奇要知道,以下两种方法之间有什么区别吗?

  1. Calling class method with in class method using self

    使用self在类方法中调用类方法

    class Test
      def self.foo
       puts 'Welcome to ruby'
      end
    
     def self.bar
      self.foo
     end
    
    end
    

    Test.bar # Welcome to ruby

    Test.bar#欢迎来到红宝石

  2. Calling class method with in class method without self

    在没有self的类方法中调用类方法

    class Test
      def self.foo
       puts 'Welcome to ruby'
      end
    
     def self.bar
      foo
     end
    
    end
    

    Test.bar # Welcome to ruby

    Test.bar#欢迎来到红宝石

1 个解决方案

#1


12  

Yes, there is a difference. But not in your example. But if foo was a private class method, then your first version would raise an exception, because you call foo with an explicit receiver:

是,有一点不同。但不是在你的例子中。但是如果foo是一个私有类方法,那么你的第一个版本会引发异常,因为你用一个显式接收器调用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

But the second version would still work:

但第二个版本仍然有效:

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"

#1


12  

Yes, there is a difference. But not in your example. But if foo was a private class method, then your first version would raise an exception, because you call foo with an explicit receiver:

是,有一点不同。但不是在你的例子中。但是如果foo是一个私有类方法,那么你的第一个版本会引发异常,因为你用一个显式接收器调用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

But the second version would still work:

但第二个版本仍然有效:

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"