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

前端 未结 5 1655
忘了有多久
忘了有多久 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:48

    test.csv:

    name,surname,no1,no2,no3,date
    Raja,Palit,77489,24,84,12/12/2011
    Mathew,bargur,77559,25,88,01/12/2011
    harin,Roy,77787,24,80,12/12/2012
    Soumi,paul,77251,24,88,11/11/2012
    

    Acces by cols:

    require 'csv'
    csv = CSV.read('test.csv', :headers=>true)
    p csv['name'] #=>["Raja", "Mathew", "harin", "Soumi"]
    
    #or even:
    t = CSV.table('test.csv')
    p t[:no1] #=> [77489, 77559, 77787, 77251]
    

    Note that in the last case the cols are accessed by their symbolized name and that strings are converted to numbers when possible.

提交回复
热议问题