Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" 
like image 353
Kashiftufail Avatar asked Jul 03 '12 14:07

Kashiftufail


People also ask

How do you get a comma-separated string from an array in C?

How to get a comma separated string from an array in C#? We can get a comma-separated string from an array using String. Join() method. In the same way, we can get a comma-separated string from the integer array.

How do you get comma-separated values in an array?

Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.

How do you convert an array to a comma-separated string in Python?

Use the join() Function to Convert a List to a Comma-Separated String in Python. The join() function combines the elements of an iterable and returns a string. We need to specify the character that will be used as the separator for the elements in the string.

How do you add comma-separated values in a string array in Java?

The simplest way to convert an array to comma separated String is to create a StringBuilder, iterate through the array, and add each element of the array into StringBuilder after appending the comma.


1 Answers

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!

like image 76
Matt Avatar answered Oct 03 '22 18:10

Matt