Graham Slick Graham Slick - 1 month ago 8
Ruby Question

Find index of a given CSV row

I have a CSV file, and I can search through it like this:

csv.find {|row| row[0] == 'MB_ID'}


It returns an object:

#<CSV::Row "MB_ID":"MB_ID">


How can I get the index of the row relatively to the CSV File ?
I tried
.index
but didn't work.

Here is a sample:

MB_ID
CATEGORIE_ARTICLE_ARTICLE_ID
COMMENTAIRE_ID
CLUB_ID
MESSAGE_ID
EXP_ID
ADH_ID
PRO_ID
LA_ID
SA_ID


So the expected result would be 1 for "MB_ID" (or 0 depending on how CSV are indexed).

I read the file using:

csv = File.read("foreign.csv")
csv = CSV.parse(csv, :headers => true)

Answer

index only works for arrays. For enumerables like CSV::Table, you have to use find_index:

csv.find_index { |row| row[0] == 'MB_ID' } #=> 0