I'm learning Smalltalk programming as I think its way ahead as an OOP programming tool. I would appreciate feedback regarding my coding of the following problem. I have a sequence of letters representing bases in a DNA and want to change the T to a U in the string. I have done this in two ways. The first uses the copyReplaceAll:with: message to the string object which changes every occurrence of 'T' to a 'U':

string copyReplaceAll: 'T' with: 'U'. 

My second method uses iteration and boolean conditions to test whether a 'T' is identified. I learned that I have to copy the string to an Array object, then iterate over that object and copy the elements to an empty array. Ideally I would like the original string object to be mutable. Am I going at this the wrong way? Here's my code:

strCopy := string asArray.
empty := Array new: strCopy size.
cntr := 1.

strCopy do: [:char | 
     (char = $T) ifTrue: [empty at:cntr put: $U ]
    ifFalse: [empty at:cntr put: char].
    cntr := cntr + 1
  • 1
    \$\begingroup\$ This would have been a good question for the [smalltalk] and [pharo] tags of Stack Overflow. Next time consider asking there too. \$\endgroup\$ Commented Jul 29, 2017 at 12:07

1 Answer 1


Since Smalltalk is super interactive also try browsing through the methods of e.g. ByteString and other classes and the different ways to search for methods and their implementors:

Browsing the ByteString class methods

You can actually run do: and at:put: on it directly, but there's also doWithIndex: for example, which looks like it will make your second bit even simpler:

string doWithIndex: [ :char :i | (char = $T) ifTrue: [ string at: i put: $U ] ].

Now, in terms of readability, the first one is of course much easier to understand. It's to the point and obvious even for readers with no knowledge of Smalltalk. The second one and the example I posted aren't (or are less so at least) - they use more complex syntax and several new concepts.

If you restrict yourself to just String I think your second approach is fine though.

  • 1
    \$\begingroup\$ Thank you Ferada for taking the time to help me with this. I can see that the doWithIndex: message makes the code neater without the need for a counter. \$\endgroup\$ Commented Jul 28, 2017 at 23:25
  • 3
    \$\begingroup\$ @awyr_agored Be aware that the expression string doWithIndex: [...] suggested by @ferada will modify your string, whereas your version left the original string unchanged and worked on a copy. \$\endgroup\$ Commented Jul 29, 2017 at 12:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.