[英]How to add whitespace between elements when printing them out in Smalltalk OrderedCollection?
I have created an OrderedCollection list an now I want to print it out by using the Transcript, like this: 我已经创建了一个OrderedCollection列表,现在我想通过使用Transcript将其打印出来,如下所示:
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. 输出是35791113,但我需要3 5 7 9 11 13,所以我需要元素之间的空格。 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. 但是我没有OrderedCollection(3 5 7 9 11 13),而是只有列表元素,没有OrderedCollection。 How to achieve this? 怎么做到这一点?
In Pharo you could simply do 在Pharo你可以做到
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 在GNU Smalltalk中,您需要更加明确
Transcript show: ((range collect: [ :each | each asString ]) join: ' ')
Finally you could simply expand what you've already tried with do:separatedBy:
最后你可以简单地展开你已经尝试过的东西do:separatedBy:
range
do: [ :each | Transcript show: each ]
separatedBy: [ Transcript show: ' ' ]
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: 例如,在Pharo中我们有#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 您可能想要做的另一件事是使用Transcript space
来获取
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
: 此外,我建议采用更通用的方法,将字符串表示形式转储到更通用的对象(如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. 获得理想的结果。
In Squeak, Pharo and Cuis you may do 在Squeak,Pharo和Cuis中你可以做到
#(3 5 7 9 11 13) do: [:each | Transcript show: each; space]
to get the result. 得到结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.