Can you think of a way to turn a string into comma-separated characters, ideally as an array? as in:
"yes" ----> [y, e, s]
"vanilla" ----> [v, a, n, i, l, l, a]
thanks!
Can you think of a way to turn a string into comma-separated characters, ideally as an array? as in:
"yes" ----> [y, e, s]
"vanilla" ----> [v, a, n, i, l, l, a]
thanks!
"yes".as(Array)
Btw arrays aren’t comma-separated. They print with comma separation but they aren’t stored that way.
But… what do you need to do with this array that you can’t do with a string? You can already do
, collect
, at
, put
etc directly on strings. So I’d suggest to try it on the string first. You might find out that .as(Array)
only wastes time.
hjh
I want to split up strings, often numbers, into individual figures
12345 >>> [1,2,3,4,5]
i always assumed arrays were actually comma-separated. i’ve been living in a lie
thanks!
a = "abc";
-> abc
a.do { |char| char.postln };
a // separated and looped over
b
c
-> abc
a.collect { |char| (char.ascii + 4).asAscii };
-> efg // each char operated on, and the result reassembled
a.at(1);
-> b
a[2];
-> c // both 'at' syntaxes work transparently
// string literals are immutable
a.put(1, $x);
ERROR: Primitive '_BasicPut' failed.
Attempted write to immutable object.
// but copy it, or do any other non-in-place operation on it,
// and it's no longer immutable
b = a.copy;
-> abc
b.put(1, $x);
-> axc
So, for instance,
"12345".do { |char|
var digitValue = char.digit;
... do something with the digit...
}
// this fails because it tries to 'collect' a new String
// and Strings may contain only characters
"12345".collect { |char|
char.digit
};
// but you can force a different collection type
b = "12345".collectAs({ |char|
char.digit
}, Array);
-> [ 1, 2, 3, 4, 5 ]
The last bit might be useful to you because it converts from a collection of ASCII characters into a collection of actual numbers. That is, the important thing about it is not that the result is displayed with commas – the important thing is that "12345".at(0)
is $1 (a Char) while, after running those three lines, b.at(0)
is 1 (an Integer).
Storage format is for the computer’s convenience. Display format is for human convenience. There are many, many cases where it’s good for these to be different.
hjh