The code goes through HTML containing courses listed in tables, where
each table has 20 columns of data. This segment of code ultimately is
supposed to create an array of arrays – i.e. each element in
raw_course_list is an array containing each of the 20 columns in one row
of the HTML file.
And one last thing: As you can see from the commented out code, the temp
array is working as intended – every time the row.css(“td”).each
completes, it’s filled with data from all the column in the HTML… The
problem occurs (I’m guessing) when I push temp to raw_course_list.
raw_course_list = Array.new
# puts "raw_course_list[0]: " + raw_course_list[0].to_s # ****
Always returns the last temp pushed, not what should be at [0] (the
first array ever pushed) ****
# print "raw_course_list.size: ", raw_course_list.size, “\n” #
Correctly increases +1 each push
temp.clear
}
puts raw_course_list.each { |i| puts i.to_s} # **** Prints out line
after line of empty arrays ****
The problem is that you’re reusing temp, and clearing it.
temp = []
result = []
%w{ one two three }.each do |word|
temp.push(word)
result.push(temp)
temp.clear
end
p result # => [[], [], []]
p result.map {|obj| obj.object_id } # => [606420, 606420, 606420]
I end up with three copies of temp inside result, and temp is empty.
Try creating the temp array inside the loop, and not clearing it. Or
let Ruby do more of the work: