[英]How `self` works in nested methods in ruby?
為了查看誰在nested methods
扮演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?
# => ""
但是從編碼數字來看,我無法理解這些對象屬於哪個類。 我嘗試了下面的代碼,並獲得了相應的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
具有""
值?
Object.new.test.show調用Object.new.test對象中的show方法。
Object.new.test返回nil(因為p返回nil),但同時它將show方法的定義添加到Object類。
由於nil是Object的子類NilClass的類,因此nil現在已將show用作方法,因此實際上可以在nil中調用show。
當您執行Object.new.test.show等同於然后
nil.show
在演出中,當您執行p“#{self}”時,實際上是在打印nil.to_s
nil.to_s is ""
這就解釋了您所看到的神秘“”。
這很簡單:
def show
p "#{self}"
end
返回nil
,即def
部分,這就是為什么test
方法返回nil
對象( NilClass
的實例)的NilClass
。 在show
方法中,您正在執行p "#{self}"
,它將返回一個字符串對象,該對象是String
類的實例。
嘗試這個 :
class FooBar
def foo
puts self.class
puts self
def bar
puts self.class
puts self
end
bar
end
end
FooBar.new.foo
我有 :
FooBar
#<FooBar:0x007fc413849818>
FooBar
#<FooBar:0x007fc413849818>
由於分配了不同的對象,因此獲得了不同的結果。
self
返回定義方法所在的對象,即使它是嵌套方法也是如此。
嘗試使用: self.class.to_s
。 因此,我想輸入其他字符,所以[:
我們都知道, self inside a method is always the object on which the method was called
。 因此,讓我們嘗試檢查其真實性。
讓我們首先從下面的代碼中查看誰是默認self
:
m=self
# => main
m.class
# => Object
好的,默認的self
是Object
類的Object
。
只是以更簡化的方式編寫了以下代碼,從描述的代碼中突出了該概念。
def test
p self.class
def show
p self.class
end
end
# => nil
在self inside a method is always the object on which the method was called
牢記self inside a method is always the object on which the method was called
僅稱為test
,如下所示。
test
Object
# => nil
是的,已返回Object
,並在其上調用了test
,這意味着以上陳述為真。
test.show
Object
NilClass
# => NilClass
由於塊def show;p self.class;end
調用test
也會返回nil
。現在nil
是NilClass
的對象。 因此,已經在NilClass
對象上調用了show
方法。 結果self
是NilClass
。 上面的陳述再次成立。
通過上述概念,嘗試以微小的步驟達到實際目標:
def test
p "1. # => #{self}"
def show
p "2. # => #{self}"
end
end
# => nil
test
"1. # => main" #<~~ main is an object of class Object,on which test was called from IRB.
# => nil
test.show
"1. # => main"
"2. # => " #<~~ nil("" means nil.to_s) is an object of Nilclass,on which show was called from IRB.
# => "2. # => "
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.