How to split CSV fragment in Ruby?

I have this line as an example from a CSV file:

2412,21,"Which of the following is not found in all cells?","Curriculum","Life and Living Processes, Life Processes",,,1,0,"endofline"

I want to split it into an array. The immediate thought is to simply divide by commas, but some of the lines have commas in them, for example, "Life and Life Processes, Life Processes", and they should remain the same elements in the array. We also note that there are two commas between which there is nothing - I want to get them as empty lines.

In other words, the array I want to get is

[2412,21,"Which of the following is not found in all cells?","Curriculum","Life and Living Processes, Life Processes","","",1,0,"endofline"]

I can think of hacking methods related to eval, but I hope someone can come up with a clean regex to do this ...

cheers max

+3
source share
5
str=<<EOF
2412,21,"Which of the following is not found in all cells?","Curriculum","Life and Living Processes, Life Processes",,,1,0,"endofline"
EOF
require 'csv' # built in

p CSV.parse(str)
# That it! However, empty fields appear as nil.
# Makes sense to me, but if you insist on empty strings then do something like:
parser = CSV.new(str)
parser.convert{|field| field.nil? ? "" : field}
p parser.readlines
+3
text=<<EOF
2412,21,"Which of the following is not found in all cells?","Curriculum","Life and Living Processes, Life Processes",,,1,0,"endofline"
EOF
x=[]
text.chomp.split("\042").each_with_index do |y,i|
  i%2==0 ?  x<< y.split(",") : x<<y
end
print x.flatten

$ ruby test.rb
["2412", "21", "Which of the following is not found in all cells?", "Curriculum", "Life and Living Processes, Life Processes", "", "", "", "1", "0", "endofline"]
+2

This morning I came across a CSV Table Importer project for Ruby-on-Rails. In the end, you will find the code useful:

Github tableimporter

+1
source

Source: https://habr.com/ru/post/1769537/


All Articles