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

  • 本文关键字:self 类方法 区别 之间 调用 Ruby ruby
  • 更新时间 :
  • 英文 :


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

  1. 使用 self 调用类方法与类方法相同

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

    Test.bar # 欢迎使用 Ruby

  2. 使用不带 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"

最新更新