Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First n characters of string or whole string; without SubscriptOutOfBounds

In Pharo 7, I am trying to get the first number of characters of a string, or just the whole string (if the requested number of characters exceeds the length of the string).

However, the following example results in an error, whereas I just want it to return the whole string:

    'abcdef' copyFrom: 1 to: 30. "=> SubscriptOutOfBounds Error"
    'abcdef' first: 30. "=> SubscriptOutOfBounds Error"
    'abcdef' first: 3. "=> 'abc'; OK"

Is there a method that will just return the whole string if the requested length exceeds the string length?

As a workaround, I did the following, to check first the length of the string and only send first: if the length exceeds the maximum length, but it's not very elegant:

label := aTaskbarItemMorph label size < 30 ifTrue: [ aTaskbarItemMorph label ] ifFalse: [ aTaskbarItemMorph label first: 30 ].
like image 884
mydoghasworms Avatar asked Feb 04 '19 12:02

mydoghasworms


2 Answers

MethodFinder to the rescue

We should also bear in mind that for cases like this one we have the MethodFinder in Pharo. You use it by evaluating the examples you have. In our case

MethodFinder methodFor: #(('abcdef' 30) 'abcdef' ('abcdef' 3) 'abc')

will produce

"'(data1 contractTo: data2) (data1 truncateTo: data2) '"

which contains the already mentioned #truncateTo: and adds #contractTo:. Note that the latter implements other flavor of shortening techniques, namely

'abcdef' contractTo: 6 "'a...f'"

probably not what you want today, but a piece of information that might prove useful in the future.


Syntax

The syntax of MethodFinder requires an Array of length 2 * #examples, where each of the examples consists of a pair (input arguments, result).

Interestingly, Squeak braces make it easy to provide dynamically created examples:

input := 'abcdef'.
n := 1.
MethodFinder methodFor: {
     {input. input size + n}. input.
     {input. input size - n}. input allButLast
}

will also find truncateTo:.

like image 72
Leandro Caniglia Avatar answered Oct 10 '22 09:10

Leandro Caniglia


String>>truncateTo:

'abcdef' truncateTo: 30. "'abcdef'"
'abcdef' truncateTo: 3. "'abc'"
like image 26
Peter Uhnak Avatar answered Oct 10 '22 08:10

Peter Uhnak