views:

715

answers:

2

Say I have a string with comma delimited values enclosed in single quotes that may or may not include commas, like this:

"'apples,bananas','lemons'"

and I want to split that into an array

["apples,bananas", "lemons"]

Apparently, if I split(',') the string I get

[ "'apples", "bananas'", "lemons" ]

which I don't understand. The only way to do this that I've come up with is

a = []
s = "'apples,bananas','lemons'"
s.scan(/\'([^\']+)\'/){|i| a << i[0]}

# result is ["apples,bananas", "lemons"]

But is there a more elegant way? Is there something with the split method that I don't get, which is causing the strange result?

+1  A: 

The result of #split is perfectly normal, the method isn't supposed to tokenize the string in any way. Pick the way you know that works over an elegant one.

Sii
+6  A: 

Actually split is working the way it's supposed to. But it seems like you're trying to split comma separated values. And there's already a solution for it in Ruby's stdlib:

http://www.ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html

Or if you want an external libray (that supposed to be better, faster, ...) use FasterCSV.

ujh
The CSV lib seems helpful. If the string would be formatted as s = "\"apples,bananas\", lemons" (using escaped double quotes instead of single quotes) I could do CSV::parse_line(s) and get the desired result. This might be a possible solution.
morbaq
At least with FasterCSV, you can parse the existing string without reformatting. require 'fastercsv'; "'apples,bananas','lemons'".parse_csv(:quote_char => "'") yields ["apples,bananas", "lemons"], which is what you're looking for, I believe.
Greg Campbell
Greg, you're right. 1 up for that recipe.
morbaq