Elegant way to delete the last part of a line?

In Smalltalk, if the string 'OneTwoThree' is given, I would like to remove the last part of Three 'OneTwoThree' . 'Three' . 'OneTwo' , In Squeak method finder: 'OneTwoThree' . 'Three' . 'OneTwo' 'OneTwoThree' . 'Three' . 'OneTwo' 'OneTwoThree' . 'Three' . 'OneTwo' .

The best I can come up with is:

'OneTwoThree' allButLast: 'Three' size ,

but it does not feel very Smalltalk-ish because it uses the length of the substring, not the substring. How do you code it?

+7
smalltalk
source share
4 answers
 'OneTwoThree' readStream upToAll: 'Three' 
+8
source share

I usually use #copyReplaceAll: with: method if the last line is not repeated elsewhere in the original line, of course:

 'OneTwoThree' copyReplaceAll: 'Three' with: '' 
+6
source share

There must be a #removeSuffix: method in the Moose project, which removes the given suffix, if present.

+2
source share

If you need everything after deleting only the last event:

| original cutOut lastEnd currentEnd modified |

original: = 'OneTwoThree'.
cutOut: = 'Three'.
lastEnd: = 0.
[currentEnd: = lastEnd.
lastEnd: = original indexOf: cutOut startAt: lastEnd +1.
lastEnd = 0] whileFalse.

modified: = currentStart> 0 ifTrue: [original first: currentEnd] ifFalse: [original copy]

+1
source share

All Articles