Tuesday, April 28, 2009

joining arrays with a string.

In python, I can say "-".join([1,2,3]) and it returns "1-2-3".

I was surprised to find that this wasn't available in squeak!

After hunting around the image for a while, I rolled my own version specific to my class. Then I realized what squeak really wanted me to do was add methods to the system-wide Collection class.

I mentioned what I was doing on #squeak and keithy_ mentioned Join. Turns out there's a whole bunch of public squeak code that isn't in the Universe, SqueakMap, or the default Monticello package browser.

Instead, this issue was tracked as bug 4874 in mantis.

From there I found http://www.squeaksource.com/SplitJoin.html

There's some code right on the page for adding it to your Monticello reposotiry list, but since I didn't see that, I added the URL (minus the .html) manually by clicking the "+Repository" button in Monticello and editing the URL. Then I clicked "Open" and was able to install the SplitJoin package easily.

SplitJoin adds a join: method to OrderedCollection as well as to String. The one on OrderedCollection is definitely not what you want. Instead, use the one on String, just like in python:

'-' join: #(1 2 3).

BTW: the mantis bug is marked "testing" and "fixed in 3.11" so probably this will be standard in the upcoming squeak release.

PS: turns out join: is actually implemented for all objects in SplitJoin. So if you say #(1 2 3) join: '-' you'll get back #($-) (an array containing a single minus character). This is because the #(1 2 3) array is actually inserting itself between each character of the string, but since there's only one character, you just get one character back. #(1 2 3) join: 'abc' returns #($a 1 2 3 $b 1 2 3 $c).

No comments:

Post a Comment