How to copy no more than n elements of a collection in Smalltalk?

Is there an elegant single-line font for copying no more than n elements in a collection?

I find a record of the following bulky:

limit := collection size min: n.
copy := collection copyTo: limit

Is there a better way?

Change - and also a bit more complicated: copy no more than the last n elements

+4
source share
3 answers

There are also streaming messages:

'foobar' readStream next: 3.
'foobar' readStream next: 10.

In Squeak / Pharo use next:, it is automatically cut off when the number of available items is not requested.

In other dialects, such as VW and Dolphin, use a more explicit nextAvailable:one to avoid error.

+6
source

, , , :

SequenceableCollection>>#copyAtMost: n
   ^ self first: (self size min: n)

:

collection := 1 to: 100.
collection copyAtMost: 101
+5

, :

aCollection first: (aCollection size min: n)

aCollection last: (aCollection size min: n)
+5

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


All Articles