![](/img/trans.png)
[英]Why does using an unset variable as the array index return element 0 in Bash?
[英]In Ruby, why does plugging in a variable assigned to an array index return undefined?
我正在學習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]]
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.