Robert Klemme
8/7/2006 9:37:00 AM
Peña wrote:
> fr joey:
> # Whats wrong with:
> # sum = [1,2,3,4,5].inject{|sum,e| sum+e } ?
>
> dry.
> i still think inject should update sum before exit.
No, just the fact that you name a variable "sum" doesn't imply
semantics. In your code "sum" is just a block variable. And it's
updated each time the block is invoked. So the last time the block is
invoked "e" has the value of the last element and "sum" equals the sum
of all preceding arguments. You should rather do this in order to avoid
confusion.
sum = [1,2,3,4,5].inject {|s,x| s+x}
If you want to stick with your original code where you predeclared "sum"
there is absolutely no point in using #inject. In that case #each is
much better:
sum = 0
(1..5).each {|x| sum += x}
An additional note: if you want to be your code to safe for empty
collections you should use this form
sum = enum.inject(0) {|s,x| s+x}
Kind regards
robert