Username Username - 7 months ago 24
Ruby Question

In a CSV, how do I loop through column names and get their position in the header row?

I have a CSV file that looks something like this:

ID,Name,Age
1,John,99


I've
require
d
csv
in my Ruby script.

But using
CSV
, how do I loop thru the header row? How do I find the position number for
ID
,
Name
and
Age
?

Answer

After copying your data to a file x.csv, I executed the following in irb:

2.3.0 :009 > require 'csv'
 => false
2.3.0 :010 > csv = CSV.read 'x.csv'
 => [["ID", "Name", "Age"], ["1", "John", "99"]]
2.3.0 :010 > csv = CSV.read 'x.csv'
 => [["ID", "Name", "Age"], ["1", "John", "99"]]
2.3.0 :011 > header_line = csv[0]
 => ["ID", "Name", "Age"]
2.3.0 :012 > header_line[0]
 => "ID"
2.3.0 :013 > header_line[1]
 => "Name"
2.3.0 :014 > header_line[2]
 => "Age"

...so this is one way you can do it; use read to get an array of arrays, and assume the first is an array of column headings.

In the real world you probably won't want to read the entire file into memory at once and would use CSV.foreach:

#!/usr/bin/env ruby

data = []
CSV.foreach('x.csv') do |values_in_row|
  if @column_names  # column names already read; this must be a data line
    data << values_in_row  # just an example
    # do something with values_in_row
  else
    @column_names = values_in_row
  end
end

puts "Column names are: #{@column_names.join(', ')}"
puts "Data lines are:"
puts data
Comments