In Ruby, how to read data column wise from a CSV file?

前端 未结 5 1623
忘了有多久
忘了有多久 2020-12-30 01:15

I know how it is done row-wise

CSV.foreach(filename.csv) do |row|
  puts \"#{row}\"
end

But I am completely lost column wise?

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-30 01:54

    Bored so decided to cook up an alternate solution here. Only works (here) if the first row has the max number of columns

    columns = {}
    rows.first.each_with_index do |col, i|
      columns[i] = []
    end
    rows.each do |row|
      row.each_with_index do |cell, i|
        columns[i] = columns[i] + [cell]
      end
    end
    

    Now you should be able to access each column by its index

提交回复
热议问题