0

I have a following csv:

"id","title"
1070,"\"stern\" Abo"
1071,"stern_de"

To read only the first column I can do following:

CSV.foreach(a, :headers => true, :quote_char => "'") do |row| b.push(row[0]) end

However, I want to address the column rather by column name than by index.

The above command return me an array b filled with nils.

CSV.foreach(a, :headers => true, :quote_char => "'") do |row| b.push(row['title']) end
Alina
  • 2,191
  • 3
  • 33
  • 68

1 Answers1

0

Your issue is occurring because you have "cheated" in how you are parsing the escaped quotation marks in the CSV file, by use of :quote_char => "'". The quote character is not ', it is still just the default of "!

Without fixing this mistake, you could access each column by its header, by including the extra quotation mark that you've inadvertently included:

CSV.foreach(a, :headers => true, :quote_char => "'") do |row|
  row['"title"']
end

However, as outlined in this post, a better solution is to first convert the data into a valid ruby CSV structure and then access it as normal - i.e. something like:

text = File.read('your-input-file.csv').gsub(/\\"/,'""')
CSV.parse(text, headers: true) do |row|
  b.push(row['title'])
end
Community
  • 1
  • 1
Tom Lord
  • 27,404
  • 4
  • 50
  • 77
  • How big are the files you're dealing with? Are you actually likely to hit this limit? If so, you can - as the linked answer suggests - just modify the code to read the file one line at a time. – Tom Lord Apr 28 '17 at 13:42