How to load CSV with two columns in Ruby and store it in 2 arrays

I want to load a CSV file with two columns (each with a name and a string of numbers) and only store the numbers of the two columns in two different arrays. Then I want to do some calculations with the data in those two columns, using two arrays to store the numbers of each column.

This is what I have:

require 'csv'
filename = 'file.csv'
csv_data = CSV.read(filename, :col_sep => ";")
csv_data.shift
csv_data.each_with_index { |column, index_c|
  average = 0
  column.each_with_index{ |element, index_e|
    csv_data[index_c][index_e] = element.to_i
  }
}
csv_data = csv_data.transpose

      

How do I split columns csv_data

into two arrays?

+3


source to share


1 answer


This should do the trick for you, creating your two column arrays without wasting data storage, flushing the entire file into csv_data entirely.



require 'csv'
filename = 'file.csv'
arr1 = []
arr2 = []
CSV.foreach(filename, :col_sep => ";", :return_headers => false) do |row|
  arr1 << row[0].to_i
  arr2 << row[1].to_i
end

      

+3


source







All Articles