Ruby 调用对象自己的私有方法失败?
Ruby Failure while calling an objects own private method?
方法puts在模块Kernel中被定义为private。所以没有人可以执行其他对象 put - 这很清楚。但是为什么下面的例子不是 运行 尽管 self 和 slf 有相同的 ID?他们不是同一个对象吗?
>> slf = self
>> slf.puts
(irb):206:in `<main>': private method `puts' called for main:Object (NoMethodError)
from C:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/irb-1.3.5/exe/irb:11:in `<top (required)>'
from C:/Ruby30-x64/bin/irb:25:in `load'
from C:/Ruby30-x64/bin/irb:25:in `<main>'
>> p self.object_id
320
>> p slf.object_id
320
Ruby 中的私有方法只能通过无接收器消息发送调用,即使用 self
作为隐式接收器,或使用文字伪变量 self
作为显式接收器。
IOW,允许的两种方式是
foo(args)
和
self.foo(args)
.
在您的示例中,您发送的消息接收方是局部变量 slf
,即既不是隐式的,也不是文字伪变量 self
,因此,调用私有方法是不允许。
方法puts在模块Kernel中被定义为private。所以没有人可以执行其他对象 put - 这很清楚。但是为什么下面的例子不是 运行 尽管 self 和 slf 有相同的 ID?他们不是同一个对象吗?
>> slf = self
>> slf.puts
(irb):206:in `<main>': private method `puts' called for main:Object (NoMethodError)
from C:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/irb-1.3.5/exe/irb:11:in `<top (required)>'
from C:/Ruby30-x64/bin/irb:25:in `load'
from C:/Ruby30-x64/bin/irb:25:in `<main>'
>> p self.object_id
320
>> p slf.object_id
320
Ruby 中的私有方法只能通过无接收器消息发送调用,即使用 self
作为隐式接收器,或使用文字伪变量 self
作为显式接收器。
IOW,允许的两种方式是
foo(args)
和self.foo(args)
.
在您的示例中,您发送的消息接收方是局部变量 slf
,即既不是隐式的,也不是文字伪变量 self
,因此,调用私有方法是不允许。