Split CSV-style string with Ruby

I have data from a CSV file that is already loaded into memory. So I might have something like this:

csv_string = 'Value 1,Value 2,"Hey, it\ value 3!",Value 4 has "some quotes"'

Obviously, I do not want to do csv_string.split(","). Since this is similar to CSV-style line splitting, this method may not be quite unusual, I was wondering if there is already an existing solution there.

+3
source share
2 answers

For analysis, CSV Ruby comes with a library csv:

require 'csv'

CSV.parse(csv_string)
# => [['Value 1', 'Value 2', "Hey, it value 3!", 'Value 4 has "some quotes"']]

Unfortunately, your line does not actually contain valid CSVs, so you really get the following exception:

# CSV::MalformedCSVError: Illegal quoting on line 1.

Since your data does not actually conform to a generally accepted standard, it is obvious that there cannot be a common parser, and you will have to write your own.

CSV, :

c = %q[Value 1,Value 2,"Hey, it value 3!","Value 4 has ""some quotes"""]

CSV.parse(c)
# => [['Value 1', 'Value 2', "Hey, it value 3!", 'Value 4 has "some quotes"']]
+9

Ruby 1.9.x FasterCSV - csv , 1.8.x, , foreach row: http://fastercsv.rubyforge.org/

0

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


All Articles