[英]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.