I am trying to create a method that stores names of and then (possibly in another method) append them to each other to make an array. Interests me is the size of the array.
To explain better let's say I have three people in a group and then I want to have a group with a fixed number of people. for instance, I need to define "addPerson" and "people group" in the code below:
| People |
People := People new.
People
addPerson: Person John;
addPerson: Person Adam;
addPerson: Person Josh.
self assert: People peopleGroup size = 3
I'm very new to Smalltalk and Pharo so this might be a very beginner question.
Let me first point out a mistake in your code so we can then focus on your question.
Given that you are sending the message new
to People
, we can assume that you already have created the class People
. There is a problem, however, in the two first lines
| People |
People := People new.
which should have been written like
| people |
people := People new.
or
| group |
group := People new.
otherwise, you would be assigning an instance of People
to the class People
itself, which would have rendered the class impossible to be reached by name. Of course, the Smalltalk compiler would prevent you from having an uppercase temporary, let alone one that collides with a class name. Still, it should be clear to you that you don't want to change the binding between the identifier People
and the class it represents.
The cascade that follows, looks partially ok, provided your class People
implements the method addPerson:
.
The last expression could be simplified to
self assert: people size = 3,
which will only require you to implement the size
method in People
so that it answers with the number of "persons" it holds.
Other suspicious messages are Person john
, etc. You should add a class side method newNamed:
in Person
and write instead:
Person newNamed: 'John'
where
newNamed: aString
^self new name: aString