我有点好奇,下面这两种方法有什么区别吗?
使用self在类方法中调用类方法
class Test def self.foo puts 'Welcome to ruby' end def self.bar self.foo end end
Test.bar
# 欢迎使用 ruby在没有自身的类方法中调用类方法
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"
关于ruby - 在类方法中使用和不使用 self 调用 Ruby 类方法有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29692457/