1

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
 else
   while (j < $n)
     temp[j] = data[j].to_i
     j = j + 1
   end
   $table << temp
   i = i + 1
   j = 0
  end
p $table
end

end

Can anyone explain this behavior and help me debug it?

1 Answer 1

2

I have edited your method. It should work.

   def self.read_file
       i = 0
       j = 0
      table = []
       n = 0
     first_line = true
     IO.foreach("data.dat") do |line|
       temp=[]
       data = line.split
       if first_line
        n = data[0].to_i
       first_line = false
       puts('Read first line')
      puts n
   else
      while (j < n)
         temp[j] = data[j].to_i
          j = j + 1
       end
    table << temp
     i = i + 1
      j = 0
   end
    p table
  end
 end
Sign up to request clarification or add additional context in comments.

2 Comments

Code-only answers are discouraged. Please at least describe the change you made, or post only the relevant part of the code.
I think issue was in temp so I have just change the place of temp variable with in do loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.