RUBY Pushing array into array overwrites all previous elements?

This function reads a file and inserts the data into a multi-dimensional array, however it seems that on every push of temp into $table, it completely overwrites every element in $table with what is in temp.

def self.read_file
i = 0
j = 0
$table = []
$n = 0
temp = []

first_line = true

IO.foreach("data.dat") do |line|
  data = line.split
  if first_line
    $n = data[0].to_i
    first_line = false
    puts('Read first line')
    puts $n
   while (j < $n)
     temp[j] = data[j].to_i
     j = j + 1
   $table << temp
   i = i + 1
   j = 0
p $table


Can anyone explain this behavior and help me debug it?

Source: ruby

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.