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 ].
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.
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:
.
String>>truncateTo:
'abcdef' truncateTo: 30. "'abcdef'"
'abcdef' truncateTo: 3. "'abc'"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With