Earlier quoted context omitted.
Or you can have a sum method that accepts a block/lambda/anonymous function as an argument. This is done in Smalltalk with detectSum. people detectSum: [ :person | person age ]. items detectSum: [ :item | item price ].
In Ruby, this would be: class Array def detectSum(&block) self.map(&block).sum end end >> [1, 2, 3].detectSum {|i| i**2} => 14 Most Ruby people though would just call #map and #sum in succession on an ad hoc basis.
detectSum: aBlock
"Evaluate aBlock with each of the receiver's elements as the argument.
Return the sum of the answers."
| sum |
sum := 0.
self do: [:each |
sum := (aBlock value: each) + sum].
^ sum
Anyway, my point still stands. Better to accept a block than to use a sum method that assumes the Array consists of numbers