Reputation: 304
I have this text:
text = '"Friend", "One, Two, Three", "something else"'
I want to convert it to an array:
array = [
"Friend",
"One, Two, Three",
"something else"
]
How can I do it in Ruby? Simple split()
won't work, since ,
may be inside some elements (like in this example). Maybe there are some libraries for that?
Upvotes: 0
Views: 233
Reputation: 168269
You should use scan
.
text.scan(/"([^"]*)"/).flatten
# => ["Friend", "One, Two, Three", "something else"]
or
text.scan(/"[^"]*"/).map{|s| s[1...-1]}
# => ["Friend", "One, Two, Three", "something else"]
Or, you can go with split
.
text[1...-1].split(/", "/)
# => ["Friend", "One, Two, Three", "something else"]
Upvotes: 2
Reputation: 3984
String#scan
with a regular expression:
text = '"Friend", "One, Two, Three", "something else"'
text.scan(/\"([,\ \w]+)\"/).flatten
#=> ["Friend", "One, Two, Three", "something else"]
Upvotes: 9
Reputation: 18843
Ruby's CSV parser won't like the space between elements in ", "
, but if you clear that out, you can use it.
> s = '"Friend", "One, Two, Three", "something else"'
> t = s.gsub(/",\s*"/, '","')
> CSV.parse t
=> [["Friend", "One, Two, Three", "something else"]]
Upvotes: 0