I have a class in Smalltalk that stores an OrderedCollection of objects. Each object has a name. I would like to iterate over the OrderedCollection objects and print out the name of each of these objects. For example, in Java I would have something like:
for(int i = 0; i < array.length; ++i) {
System.out.println(array[i].getName());
}
This is how far I got in Smalltalk, where "list" is the OrderedCollection:
1 to: list size do: [
:x | Transcript show: 'The object name:' list at: x printString; cr.
]
Your solution is good, except for two small mistakes: (1) you forgot some parenthesis and (2) the concatenation message #,
is missing:
1 to: list size do: [
:x | Transcript show: 'The object name:' list at: x printString; cr.
]
should have been
1 to: list size do: [
:x | Transcript show: 'The object name:' , (list at: x) printString; cr.
]
otherwise the Transcript
object would receive the message #show:at:
, which it doesn't understand. Also, you have to concatenate the string 'The object name: '
with (list at: x) printString
, and that's why you need the concatenation message #,
in between.
Note however that in your example there is no need to use indexes. Instead of iterating from 1
to list size
you could simply enumerate the objects in the list
collection, like this:
list do: [:object | Transcript show: 'The object name: ' , object printString; cr]
This form is usually preferred because it avoids the use of an intermediate index (x
in your example) and forces you to access the x-
th element of the collection using #at:
, all of which makes your code easier to read and modify.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With