简体   繁体   English

Ruby,为什么插入赋值给数组索引的变量返回undefined?

[英]In Ruby, why does plugging in a variable assigned to an array index return undefined?

I am learning Ruby and just solved this pyramid problem.我正在学习Ruby,刚刚解决了这个金字塔问题。 For whatever reason, I tried to change twoD[0] to the variable twoDidx (see third line).无论出于何种原因,我试图将twoD[0]更改为变量twoDidx (见第三行)。

However, when I try replacing while twoD[0].length != 1 with while twoDidx.length != 1 , I get "undefined."但是,当我尝试将while twoD[0].length != 1替换为while twoDidx.length != 1时,我得到“未定义”。 What am I not understanding about how variables work?我不了解变量的工作原理是什么? Thanks.谢谢。

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]]

There's a big difference between twoDidx and twoD[0] . twoDidxtwoD[0]之间有很大的区别。 twoDidx is a reference to a first element of twoD at the time you made an assignment while twoD[0] is the reference to the first element of twoD array at the time of execution. twoDidx在您进行赋值时对twoD的第一个元素的引用,而twoD[0]是在执行时对twoD数组的第一个元素的引用。

To make it more obvious:为了使它更明显:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM