asCamelCase for Smalltalk's String

Something that might be useful when you are doing meta-programming in Smalltalk and want to quickly create a method name in camelCase from several words. The following was colorized using Vim's :runtime! syntax/2html.vim

Put this as String >> asCamelCase (inside the converting protocol, if you like)

 1  asCamelCase
 2     "Return a copy of the receiver with leading/trailing blanks removed
 3     and consecutive white spaces condensed. Also the string is camelCased"
 4     | trimmed lastBlank |
 5     trimmed := self withBlanksTrimmed.
 6     ^ String
 7        streamContents: [:stream |
 8           lastBlank := false.
 9           trimmed do: [:c | (c isLetter and: [lastBlank])
10                    ifTrue: [stream nextPut: c asUppercase]
11                    ifFalse: [c isLetter
12                          ifTrue: [stream nextPut: c]].
13                 lastBlank := c isSeparator]]

Some test cases and their expected results:

1  testCamelCase
2     self assert: 't' asCamelCase = 't'.
3     self assert: '' asCamelCase =''.
4     self assert: 'this should be camel cased' asCamelCase = 'thisShouldBeCamelCased'.
5     self assert: 'this' asCamelCase = 'this'.
6     self assert: 'this  should also     be in camel case' asCamelCase = 'thisShouldAlsoBeInCamelCase'.
7     ^self

This method was inspired by the chapter on meta-programming in Smalltalk by Example (links to free e-book version).


comments powered by Disqus