如何创建在Pharo中存储名称的方法?

时间:2018-06-04 11:47:00

标签: smalltalk pharo

我正在尝试创建一个存储名称的方法,然后(可能在另一个方法中)将它们相互追加以形成一个数组。我感兴趣的是数组的大小。

为了更好地解释,假设我在一个小组中有三个人然后我想拥有一个拥有固定人数的小组。例如,我需要在下面的代码中定义“addPerson”和“people group”:

| People |
People := People new.
People 
    addPerson: Person John;
    addPerson: Person Adam;
    addPerson: Person Josh.
self assert: People peopleGroup size = 3

我对Smalltalk和Pharo很新,所以这可能是一个非常初学的问题。

1 个答案:

答案 0 :(得分:2)

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