Home > OS >  In Ruby, why does plugging in a variable assigned to an array index return undefined?
In Ruby, why does plugging in a variable assigned to an array index return undefined?

Time:03-04

I am learning Ruby and just solved this pyramid problem. For whatever reason, I tried to change twoD[0] to the variable twoDidx (see third line).

However, when I try replacing while twoD[0].length != 1 with while twoDidx.length != 1, I get "undefined." 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]]

CodePudding user response:

There's a big difference between twoDidx and twoD[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.

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
  • Related