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

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

Convert Comma-Separated String With No Spaces to an Array

You can convert a comma-separated Ruby string (which has no spaces) to 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 to 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 to 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"]

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.