A string from an array

Dear users,

The following code is my try to make a string from an array:

~array2str = { |anArray|
var aString; 
anArray.size.do{ |index| aString = aString ++ anArray[index].asSymbol}; 

a = ~array2str.([1, 2, 3, 4, 5, 6])

It works, but I think there might be a method to do this.
Could anyone let me know it?

I really appreciate any help you can provide.

Best regards,

I sometimes have to do the same, and haven’t found a direct method yet.
But I’ve made an extension to add the functionality to Array.
I’ve placed a file called arrayExtend.sc in the Extensions folder (Using Extensions | SuperCollider 3.12.2 Help) with the following code in it:

+ Array {
		var r = "";
		this.do{|e| r = r ++ e.asString};

This way I can call [1,2,3,'a',123].elementsToString which results to 123a123
(Recompile the class library, Cmd Shift L on Mac, so the function will be recognized)

1 Like

No need to recompile anything!
This is a great problem for a more functional programming style!

[1,2,3,4,5].collect{|v| v.asString }.reduce('++') 
 // --> "12345"

[1,2,3,4,5].collect{|v| v.asString }.reduce({|l, r| l ++ ", " ++ r }) 
// --> "1, 2, 3, 4, 5"

As a general rule of thumb, if you are taking one collection and transforming it you should never need to use an index.

1 Like

join, I believe.



Thank you very much for your kind answers. Writing an extension, using .reduce and using join are all great! They all give broad perspectives on formulating code.
Thanks again.