-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」。
什麼是「條目」? –
條目會給你數組中的值。我認爲它的ruby變量。 – Gaurav24
行..這是一種方法...我看到:) –