Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add whitespace between elements when printing them out in Smalltalk OrderedCollection?

Tags:

smalltalk

I have created an OrderedCollection list an now I want to print it out by using the Transcript, like this:

  range do:[:each|Transcript show: each].

The output is 35791113, but I need 3 5 7 9 11 13, so I need whitespaces between elements. I tryed also just..

   Transcript show: range.

But instead of this OrderedCollection(3 5 7 9 11 13), I would like to have only list elements, without OrderedCollection. How to achieve this?

like image 493
dreamPr Avatar asked Dec 11 '22 19:12

dreamPr


2 Answers

In Pharo you could simply do

Transcript show: (range joinUsing: ' ')

or the opposite

Transcript show: (' ' join: range)

This will work even if the elements are numbers.

In GNU Smalltalk you need to be more explicit

Transcript show: ((range collect: [ :each | each asString ]) join: ' ')

Finally you could simply expand what you've already tried with do:separatedBy:

range
    do: [ :each | Transcript show: each ]
    separatedBy: [ Transcript show: ' ' ]
like image 113
Peter Uhnak Avatar answered May 29 '23 08:05

Peter Uhnak


A dialect-independent solution would look like

| first |
first := true.
range do: [:each |
    first ifTrue: [frist := false] ifFalse: [Transcript show: ' '].
    Transcript show: each]

However, every dialect has already a way to do this. For example, in Pharo we have the #do:separatedBy: message:

range do: [:each | Transcript show: each] separatedBy: [Transcript show: ' ']

The other thing you might want to do is to use Transcript space to get

range do: [:each | Transcript show: each] separatedBy: [Transcript space]

Also, I would recommend a more general approach where you dump your string representation on a more general kind of object such as a WriteStream:

dump: range on: aStream
    range do: [:each | each printOn: aStream] separatedBye: [aStream space]

so now you can simply write

<receiver> dump: range on: Transcript

to get the desired result.

like image 27
Leandro Caniglia Avatar answered May 29 '23 08:05

Leandro Caniglia