[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-smalltalk] unexpected #indexOf:ifAbsent: result (was What am I
Re: [Help-smalltalk] unexpected #indexOf:ifAbsent: result (was What am I doing wrong here?)
Mon, 11 Sep 2006 21:53:01 +0000
Mozilla Thunderbird 1.0.5 (X11/20050711)
Stephen Compall wrote:
> Bram Neijt wrote:
>>The following puzzles me (in gst):
>>st> 'a/b' indexOf: '/' ifAbsent: ['ABSENT' printNl]!
> Here is the doc for (String whichClassIncludesSelector:
> #indexOf:ifAbsent:) >> #indexOf:ifAbsent:
> indexOf: anElement ifAbsent: exceptionBlock
> Answer the index of the first occurrence of anElement in the
> receiver. Invoke exceptionBlock and answer its result if no item
> is found
> Now, ask yourself, what does "anElement" mean in the context of
> Strings? Hint: the element '/' is in fact *not* present in the String
> 'a/b'. Also look around SequenceableCollection's 'basic' methods for
> the method that does what you expect here.
I'm replying in more detail because (a) this isn't the finest part of
the class library (b) you used the word "element", which I think might
be a little confusing.
Bram, the method #indexOf:ifAbsent: comes from SequenceableCollection. A
String is a Collection of Characters, but '/' is not a Character (it is
also a String), so '/' is not an element of 'a/b', nor of any String.
What you wanted was either:
'a/b' indexOf: $/ ifAbsent: [ 'ABSENT' printNl ]!
'a/b' indexOf: '/' matchCase: true startingAt: 1
'a/b' indexOfSubCollection: '/'
I said this wasn't the finest part of the class library, because (a) you
might reasonably expect #indexOf:ifAbsent: and
#indexOf:matchCase:startingAt: to be variations on a theme, and they're
not; and (b) they're all pretty wordy when all you're wanting to do is
some string wrangling.
My advice, if you are working a lot with strings, is to add a method
CharacterArray methodsFor: 'syntactic sugar'!
^self indexOfSubCollection: aSubString
Now you have:
st> 'a/b' % '/' !
which saves a lot of typing.