【问题标题】:Is there any difference between Ruby class method calling with in class method with and without self?Ruby 类方法调用在类方法中使用和不使用 self 之间有什么区别吗?
【发布时间】:2015-04-17 07:05:00
【问题描述】:

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

  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​​

【问题讨论】:

  • 请注意,这并不特定于类方法,调用实例方法也是如此。

标签: ruby


【解决方案1】:

是的,有区别。但不是在你的例子中。但是如果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"

【讨论】:

  • 另一个区别:如果有一个局部变量foofoo 将引用该变量,self.foo 将引用该方法。
猜你喜欢
  • 2010-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-31
  • 1970-01-01
  • 2016-11-19
  • 2021-06-17
相关资源
最近更新 更多