How to split a delimited string in Ruby and convert it to an array?

Neil Middleton picture Neil Middleton · Jun 10, 2009 · Viewed 325.4k times · Source

I have a string

"1,2,3,4"

and I'd like to convert it into an array:

[1,2,3,4]

How?

Answer

Shadwell picture Shadwell · Jun 10, 2009
>> "1,2,3,4".split(",")
=> ["1", "2", "3", "4"]

Or for integers:

>> "1,2,3,4".split(",").map { |s| s.to_i }
=> [1, 2, 3, 4]

Or for later versions of ruby (>= 1.9 - as pointed out by Alex):

>> "1,2,3,4".split(",").map(&:to_i)
=> [1, 2, 3, 4]