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

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!

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)