开发者

Split a CSV-style string with Ruby

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

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

Obviously I won't want to do csv_string.split(","). Since it seems like splitting a CSV-style string this way might be a not-all-that-uncommon need, I was wondering if there's a solutio开发者_StackOverflown already out there.


For parsing CSV, Ruby comes with the csv library:

require 'csv'

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

Unfortunately, your string doesn't actually contain valid CSV, so what you'll really get is the following exception:

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

Since your data doesn't actually conform to any common standard, there can obviously not be a common parser and you'll have to write your own.

Alternatively, you could change your data to be valid CSV, for example like this:

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

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


on Ruby 1.9.x FasterCSV is the default csv engine, if you are using 1.8.x you will need to include the gem, but take a look at the foreach and row parsing abilities: http://fastercsv.rubyforge.org/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜