How to separate single comma separated values ​​containing commas in Ruby

Let's say that I have a string with comma-delimited values ​​enclosed in single quotes that may or may not include commas, for example:

"'apples,bananas','lemons'"

      

and I want to split this into an array

["apples,bananas", "lemons"]

      

Apparently if I am the split(',')

string I get

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

      

which I don't understand. The only way to do this that I have 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 am not getting that is causing the weird result?

0


source to share


2 answers


In fact, the split works as it intended. But it looks like you are trying to separate comma separated values. And there is already a solution for it in Ruby stdlib:

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



Or if you want an external libray (which should be better, faster, ...) use FasterCSV .

+6


source


The result of #split is perfectly normal, the method should not disallow the string in any way. Choose a way that you know you are working on elegant.



+2


source







All Articles