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

时间:2015-04-17 07:05:01

标签: ruby

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

  1. 使用self

    在类方法中调用类方法
    class Test
      def self.foo
       puts 'Welcome to ruby'
      end
    
     def self.bar
      self.foo
     end
    
    end
    

    Test.bar#欢迎来到红宝石

  2. 在没有自我的方法中调用类方法

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

    Test.bar#欢迎来到红宝石

1 个答案:

答案 0 :(得分:12)

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