Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"] 
like image 878
Mark Szymanski Avatar asked Jan 31 '11 04:01

Mark Szymanski


People also ask

How do you convert a comma separated string to a number?

To convert a comma separated string to a numeric array:Call the split() method on the string to get an array containing the substrings. Use the map() method to iterate over the array and convert each string to a number. The map method will return a new array containing only numbers.


2 Answers

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"]] 
like image 88
Kevin Sylvestre Avatar answered Oct 08 '22 09:10

Kevin Sylvestre


require 'csv' CSV.parse_line('one,two,three,four') #=> ["one", "two", "three", "four"] 
like image 43
ephemient Avatar answered Oct 08 '22 09:10

ephemient