Mark Szymanski
Mark Szymanski

Reputation: 58170

How do I convert a comma-separated string into an array?

Is there any way to convert a comma separated string into an array in Ruby? For instance, if I had a string like this:

"one,two,three,four"

How would I convert it into an array like this?

["one", "two", "three", "four"]

Upvotes: 85

Views: 82123

Answers (3)

Kevin Sylvestre
Kevin Sylvestre

Reputation: 38092

Use the split method to do it:

"one,two,three,four".split(',')
# ["one","two","three","four"]

If you want to ignore leading / trailing whitespace use:

"one , two , three , four".split(/\s*,\s*/)
# ["one", "two", "three", "four"]

If you want to parse multiple lines (i.e. a CSV file) into separate arrays:

require "csv"
CSV.parse("one,two\nthree,four")
# [["one","two"],["three","four"]]

Upvotes: 167

ephemient
ephemient

Reputation: 205024

require 'csv'
CSV.parse_line('one,two,three,four') #=> ["one", "two", "three", "four"]

Upvotes: 18

DigitalRoss
DigitalRoss

Reputation: 146261

>> "one,two,three,four".split ","
=> ["one", "two", "three", "four"]

Upvotes: 10

Related Questions