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

I created an OrderedCollection list, now I want to print it using Transcript, for example:

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

The output is 35791113, but I need 3 5 7 9 11 13, so I need spaces between the elements. I also tried ..

   Transcript show: range.

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

+4
source share
3 answers

In Squeak, Pharo and Cuis you can do

 #(3 5 7 9 11 13) do: [:each | Transcript show: each; space]

to get the result.

+2
source

In Pharo you can just do

Transcript show: (range joinUsing: ' ')

or vice versa

Transcript show: (' ' join: range)

This will work even if the elements are numbers.

GNU Smalltalk

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

, , , do:separatedBy:

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

-

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

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

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

Another thing you can do is use Transcript spaceto get

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

In addition, I would recommend a more general approach when you upload your string representation to a more general view of an object, for example WriteStream:

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

now you can just write

<receiver> dump: range on: Transcript

to get the desired result.

+4
source

Source: https://habr.com/ru/post/1621408/


All Articles