簡體   English   中英

Ruby,為什么插入賦值給數組索引的變量返回undefined?

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

twoDidxtwoD[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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM