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

RubyArraysStringCsv

Ruby Problem Overview


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"]

Ruby Solutions


Solution 1 - Ruby

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"]]

Solution 2 - Ruby

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

Solution 3 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMark SzymanskiView Question on Stackoverflow
Solution 1 - RubyKevin SylvestreView Answer on Stackoverflow
Solution 2 - RubyephemientView Answer on Stackoverflow
Solution 3 - RubyDigitalRossView Answer on Stackoverflow