How to Convert a Comma-Separated String to an Array in Ruby?

Find out how to split a Ruby comma-separated string into an array

Depending on whether your comma-separated string has whitespaces, you can do the following to convert it into an array in Ruby:

Convert Comma-Separated String With No Spaces Into an Array

You can convert a comma-separated Ruby string (which has no spaces) into an array by using the split method, for example, like so:

"foo,bar,baz,qux".split(",")
#=> ["foo", "bar", "baz", "qux"]

Convert Comma-Separated String With Set Sequence of Repeating Spaces Into an Array

If the comma-separated string has a known number of spaces in a repeating sequence (e.g. ", "), then you can simply specify it as the delimiter to the split method, for example, like so:

"foo, bar, baz, qux".split(", ")
#=> ["foo", "bar", "baz", "qux"]

Convert Comma-Separated String With Unknown Whitespaces Into an Array

If your string has an unknown number of whitespaces before/after in any order/number, then you can use map to iterate over each item in the resulting array (from split) and use strip to trim any whitespaces:

"  foo  ,   bar,baz,  qux   ".split(",").map { | item | item.strip }
#=> ["foo", "bar", "baz", "qux"]

This also works as expected when there's a set sequence of repeating spaces in the string. For example:

"foo, bar, baz, qux".split(",").map { | item | item.strip }
#=> ["foo", "bar", "baz", "qux"]

Hope you found this post useful. It was published . Please show your love and support by sharing this post.