我正在學習 Ruby,剛剛解決了這個金字塔問題。無論出于何種原因,我試圖更改twoD[0]為變數twoDidx(見第三行)。
但是,當我嘗試用 替換while twoD[0].length != 1時while twoDidx.length != 1,我得到“未定義”。關于變數如何作業,我不了解什么?謝謝。
def pyramid_sum(base)
twoD = [base]
twoDidx = twoD[0]
while twoD[0].length != 1
arr = twoD[0].map.with_index do |num, idx|
if idx != twoD[0].length - 1
num twoD[0][idx 1]
end
end
arr = arr.compact
twoD.unshift(arr)
end
return twoD
end
print pyramid_sum([1, 4, 6]) #=> [[15], [5, 10], [1, 4, 6]]
uj5u.com熱心網友回復:
twoDidx和之間有很大區別twoD[0]。twoDidx是對twoD 您進行賦值時twoD[0]的第一個元素的參考,而是在twoD執行時對陣列的第一個元素的參考。
為了更明顯:
array = [1]
first = array[0] # Here you just assign 1 to the variable
array = [100]
first #=> 1
array[0] #=> 100
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/437210.html
