[Newbies] Quick noob snippets

Bert Freudenberg bert at freudenbergs.de
Tue May 20 09:53:40 UTC 2008


On 20.05.2008, at 05:30, Sven Schott wrote:

> c := OrderedCollection newFrom: { 1. 5. 8. 45. 23. 3. 20 }.
> String newFrom: c
>
> but I get the following: 'Error: Improper store into indexable  
> object'. What I was expecting was:
>
> 1584523320
>
> I eventually figured that it was because I was using Ints instead of  
> Characters because this works fine:
>
> str := OrderedCollection newFrom: { $a. $g. $t. $e }.
> str as: String
>
> So, the question is why do I get the error?


Because generally in Smalltalk we prefer to be explicit about what  
should happen, and have an error raised when something is unexpected,  
rather than silently second-guessing the programmer's intention.

For example, I would not have expected '1584523320' as a result but a  
String made of Characters encoded using the integers given (i.e., 45  
would be $- because 45 is the Unicode value for "-").

I'd write your example like this

	#(1 5 8 45 23 3 20) inject: '' into: [:string :each | string, each  
asString]

and to get my behavior:

	String withAll: (#(1 5 8 45 23 3 20) collect: [:c | c asCharacter])

The difference is that in the first example, each element is converted  
to a String (#asString) and then concatenated using the #, method of  
String, in the second each element is converted to a Character  
(#asCharacter) and then a new String is formed out of the resulting  
array of characters.

Note that for literal objects you should use the literal array syntax  
as I did above. The "brace arrays" are meant for putting expressions  
between the dots, evaluated each time the code is executed (literal  
arrays are compiled only once so they are vastly more efficient).

- Bert -




More information about the Beginners mailing list