In Ruby, how to read data column wise from a CSV file?
This is the solution guys:
CSV.foreach(filename).map { |row| row[0] }
Sorry for posting it in the correct format so late.
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.
Transpose your CSV file. By doing this your rows covert to column and viceversa. Below a simple example of transpose.
irb(main):001:0> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]].transpose
=> [["1", "4", "7"], ["2", "5", "8"], ["3", "6", "9"]]