tags:

views:

86

answers:

2

For example, suppose I have this:

001, "john doe", "male", 37, "programmer", "likes dogs, women, and is lazy"

The problem is that the line is only supposed to have 6 fields. But if I separate it with split I get more, due to the comma being used improperly to separate the fields.

Right now I'm splitting everything, then when I get to the 5-th index onward I concatenate all the strings. But I was wondering if there was a split(",",6) or something along these lines.

+2  A: 
sepp2k
As far as i can tell, with Shellwords.split I can't specify the separator or the number of splits.
zxcvbnm
Well, my thinking was that you didn't need to specify the number of splits because shellwords will not split quoted parts. However I did mess up about the separator, shellwords uses spaces, not commas :-(
sepp2k
+6  A: 

Ruby has a CSV module in the standard library. It will do what you really need here (ignore commas in doubles quotes).

require 'CSV.rb'
CSV::Reader.parse("\"cake, pie\", bacon") do |row| p row; end

result:

["cake, pie", " bacon"]
=> nil

You might want to strip the results if you're dim like me and stick whitespace everywhere.

Jesse Millikan