How do I convert an array of strings into a comma-separated string?

I have an array:

array = ["10", "20", "50", "99"]

And I want to convert it into a simple comma-separated string list like this:

"10", "20", "50", "99"

array.join(',') will almost do what you want; it will not retain the quotes around the values nor the spaces after.

For retaining quotes and spaces: array.map{|item| %Q{"#{item}"}}.join(', ') This will print "\"10\", \"20\", \"50\", \"99\"". The escaped quotes are necessary assuming the question does in fact call for a single string.

Documentation on the %Q: string literals.

You could use inspect as suggested in another answer, I'd say that's personal preference. I wouldn't, go look at the source code for that and choose for yourself.

Useful aside: array.to_sentence will give you a "1, 2, 3 and 4" style output, which can be nice!


["10", "20", "50","99"].map(&:inspect).join(', ') # => '"10", "20", "50", "99"'

Here:

array.map {|str| "\"#{str}\""}.join(',')

Several answers have offered solutions using #map, #inspect, #join. All of them fail to get certain details of CSV encoding correct for edge cases involving embedded commas and/or string delimiters in the elements.

It's probably a better idea to use the stdlib class CSV then to roll your own.

irb> require 'csv'
=> true
irb> a = [10,'1,234','J.R. "Bob" Dobbs',3.14159]
=> [10, "1,234", "J.R. \"Bob\" Dobbs", 3.14159]
irb> puts a.to_csv
10,"1,234","J.R. ""Bob"" Dobbs",3.14159

The map.join solutions are sufficient if this encoding doesn't need to care about embedded delimiters, or is intended for some internal representation only, but they will fail if generating data for exchange with other programs that expect Comma Separated Values (CSV) as a generally understood representation.