Search code examples
collectionssmalltalk

How to copy at most n collection elements in Smalltalk?


Is there an elegant one-liner to copy at most n elements in a collection?

I find writing the following cumbersome:

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

Is there a better way?

Edit - and also a bit harder problem: copy at most the last n elements


Solution

  • There are also the stream messages:

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

    In Squeak/Pharo use next:, it will automatically truncate when there is not as many element available as requested.

    In other dialects like VW & Dolphin use the more explicit nextAvailable: to avoid an error.