,看看誰是打在nested methods
的self
的作用,我想下面的代碼:`self`在嵌套方法中如何在ruby中工作?
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?
# => ""
但是從編碼的數字,我無法理解這些對象屬於哪個類。我試了下面的代碼,並得到了各自的class
名稱。
Object.new.test.class
"#<Object:0x000000021ff3b8>"
# => NilClass
Object.new.test.show.class
"#<Object:0x000000020660b0>"
""
# => String
因此,誰能幫助我瞭解上面的代碼如何產生這些class
名字的概念?
編輯
在這裏,我試着問我的問題更具體的方式:
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
有""
價值?
'+ 1'給你,爲你'nil.show'解釋。 – 2013-02-26 20:46:22