How to convert comma separated string to array?

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

"one,two,three,four" 

How to convert it to an array like this?

 ["one", "two", "three", "four"] 
+49
string arrays ruby csv
Jan 31 '11 at 4:00
source share
3 answers

Use the split method to do this:

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

If you want to ignore the use of leading / trailing space, use:

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

If you want to parse several lines (for example, a CSV file) into separate arrays:

 require "csv" CSV.parse("one,two\nthree,four") # [["one","two"],["three","four"]] 
+96
Jan 31 '11 at 4:01
source share
 require 'csv' CSV.parse_line('one,two,three,four') #=> ["one", "two", "three", "four"] 
+15
Jan 31 '11 at 4:12
source share
 >> "one,two,three,four".split "," => ["one", "two", "three", "four"] 
+9
Jan 31 2018-11-11T00:
source share



All Articles