【发布时间】:2012-06-04 10:25:36
【问题描述】:
Ruby 作为一种面向对象的语言。这意味着无论我发送什么消息,我都会严格将其发送到类的某个对象/实例上。
例子:
class Test
def test1
puts "I am in test1. A public method"
self.test2
end
def test2
puts "I am in test2. A public Method"
end
end
有道理我在 self 对象上调用方法 test2
但我不能这样做
class Test
def test1
puts "I am in test1. A public method"
self.test2 # Don't work
test2 # works. (where is the object that I am calling this method on?)
end
private
def test2
puts "I am in test2. A private Method"
end
end
当test2 是public method 时,我可以在self 上调用它(很公平,一个发送给self 对象的方法)。但是当test2 是private method 时,我不能自己调用它。那么我发送方法的对象在哪里?
【问题讨论】:
-
但是在这两种情况下你都可以在没有
self.的情况下调用test2。 -
这在 Ruby 2.7 中已更改,如果
test2是私有的,现在也允许self.test2。详情请见my answer。