[Newbies] Case insensitive string sort.

Ron Teitelbaum Ron at USMedRec.com
Fri Mar 2 02:50:13 UTC 2007


Hi Blake,

Not that I know of, it looks like you did it properly.  But as long as we
are on the subject there is a very cool trick to do multiple attribute
sorting I thought maybe I could share.

Normally to do multiple attributes sorting you compare the first elements
then if the first elements are equal you check the second elements.  This
works fine but you end up running into huge blocks of code when you have
more then one two elements.  

Someone showed me something that is really cool.  I spent a lot of time
proving that it wouldn't work but finally I agreed it actually does.

Here's the trick!  It is 1 asCharacter.  If you separate your attributes by
a value that guaranteed to sort to the top you can make one big string and
use it to sort.

So say you need to sort by last name, first name then middle initial.

You can create a sort string by: 

^sortString
	"return a string used for sorting names in a sorted collection"
	^self lastName, 1 asCharacter asString, self firstName, 1
asCharacter asString, self middleInitial.

(It should go without saying that each ivar needs to be initialized as a
string).

Then you just sort: 

	names asSortedCollection: [:a :b | a sortString < b sortString].

Of course you could add asUppercase if it affects your sort.

Now don't take my word for this!  I didn't believe it at first.

Happy coding!

Ron Teitelbaum
President / Principal Software Engineer
US Medical Record Specialists 

> -----Original Message-----
> From: beginners-bounces at lists.squeakfoundation.org [mailto:beginners-
> bounces at lists.squeakfoundation.org] On Behalf Of Blake
> Sent: Thursday, March 01, 2007 7:59 PM
> To: A friendly place to get answers to even the most basic questions
> aboutSqueak.
> Subject: [Newbies] Case insensitive string sort.
> 
> I'm using this to sort a string case-insensitively:
> 
> 'abcCBA' sortBy: [:a :b | a asUppercase < b asUppercase]
> 
> It works fine.
> 
> My question is, am I missing some built-in feature that does this, or is
> this idiomatic?
> 
> 	===Blake===
> _______________________________________________
> Beginners mailing list
> Beginners at lists.squeakfoundation.org
> http://lists.squeakfoundation.org/mailman/listinfo/beginners




More information about the Beginners mailing list