2013-10-29 44 views
-1
class Array 
    def total_zeros index = entries.length-1, total = 0 
    p "total entries = #{entries.length}" 
    i = 0 
    if index >= 0 
     p "in if block" 
     i = i+1 
     total_zeros index-1, total 
    end 
    p "hello #{i}" 
    end 
end 

a = [0,1,2] 
p a.total_zeros 

這是我的樣本輸出:Ruby遞歸:得到一些奇怪的輸出。

"total entries = 3" 
"in if block" 
"total entries = 3" 
"in if block" 
"total entries = 3" 
"in if block" 
"total entries = 3" 
"hello 0" 
"hello 1" 
"hello 1" 
"hello 1" 
nil 

任何人可以幫我瞭解這個代碼?我無法理解爲什麼最後一行「hello」打印了四次。這是一個遞歸,只有在i等於4時纔會打印「hello」。

+0

什麼是「條目」? –

+0

條目會給你數組中的值。我認爲它的ruby變量。 – Gaurav24

+0

行..這是一種方法...我看到:) –

回答

2

「hello」打印4次,因爲您在外部調用它一次,然後因爲遞歸而再多次打印3次。所有的函數調用都必須退出,所以你會得到一個hello打印。

至於爲什麼i不具備值4 - i的範圍僅限於該方法。該方法被調用4次,4個不同的整數被初始化爲零並遞增1。

+0

4個不同的整數初始化爲零?整數是即時值,因此永遠不會初始化。 – vgoff