我有点好奇想知道,以下两种方法有什么区别吗?
-
使用 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"