为了查看谁在嵌套方法
中扮演self
的角色,我尝试了以下代码:
def test
p "#{self}"
def show
p "#{self}"
end
end
# => nil
作为效果,我得到了以下两个对象:
Object.new.test
"#<Object:0x00000002212d78>"
# => nil
Object.new.test.show
"#<Object:0x00000002205330>" #<~~~ this is self understood
"" #<~~~ how this one came?
# => ""
但是从编码的数字中,我无法理解这些对象属于哪个类。我尝试了下面的代码并获得了各自的类
名称。
Object.new.test.class
"#<Object:0x000000021ff3b8>"
# => NilClass
Object.new.test.show.class
"#<Object:0x000000020660b0>"
""
# => String
那么谁能帮助我理解上述代码如何生成这些类
名称的概念?
编辑
在这里我尝试以更具体的方式提出我的问题:
def test
p "First level # => #{self}"
def show
p "Second level # => #{self}"
end
end
# => nil
Object.new.test.show
"First level # => #<Object:0x000000014a77b0>"
"Second level # => "
# => "Second level # => "
Object.new.test.show.class
"First level # => #<Object:0x0000000130ef70>"
"Second level # => "
# => String
为什么 p "Second level # => #{self}"
语句 self
具有 ""
值?
最佳答案
Object.new.test.show调用Object.new.test对象中的show方法。
Object.new.test返回nil(就像p返回nil一样),但同时它在Object类中添加了show方法的定义。
由于 nil 属于 NilClass 类,而 NilClass 是 Object 的子类,因此 nil 现在已作为方法 show,因此您实际上可以在 nil 中调用 show。
当你执行 Object.new.test.show 时相当于执行
nil.show
当你在 show 中执行 p "#{self}"时,实际上是在打印 nil.to_s
nil.to_s is ""
这就解释了你看到的那个神秘的“”。
关于ruby - `self` 在 ruby 的嵌套方法中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15096016/