steel steel - 1 year ago 96
Ruby Question

Split string into an array by comma, unless comma is inside quotes

Given a string of an array in Ruby with some items in quotes that contain commas:

my_string.inspect
# => "\"hey, you\", 21"


How can I get an array of:

["hey, you", " 21"]

Answer Source

The Ruby standard CSV library's .parse_csv, does exactly this.

require 'csv'
"\"hey, you\", 21".parse_csv
# => ["hey, you", " 21"]