[Newbies] Re: Array questions

Andreas Raab andreas.raab at gmx.de
Sat Apr 24 00:03:10 UTC 2010


On 4/23/2010 3:48 PM, Jerome Peace wrote:
>> Second, how would i make a method that will return the
>> number of integers in
>> the array different from the integer parameter
>>
>> anArray howmany: 5   should return how many
>> elements in the array are
>> different from the number
>
> howMany: anItem
>
> ^(self reject: [ :each |
>     each = anItem ]) size .

Better:

howManyAreNot: anItem
	"Answer the number of elements different from anItem"

	^self count:[:each| each ~= anItem]

Why is that better? 3 reasons:
1) The method has a comment.
2) The method name tells you what the method does - the spec said to 
answer the number of elements that are NOT the argument; the method name 
should reflect that.
3) It uses #count: instead of #reject: making it more compact.

Do note that 1) and 2) really go together. Having a method called 
#howMany: that returns how many items are NOT in the collection and no 
comment clarifying whether the method is wrongly named or simply buggy 
is really problematic.

Cheers,
   - Andreas


More information about the Beginners mailing list