[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: inject does not inject last value

Peña, Botp

8/7/2006 8:11:00 AM

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.

kind regards -botp

5 Answers

Gregor Kopp

8/7/2006 8:25:00 AM

0

Hm...

irb(main):001:0> a = 0
=> 0
irb(main):002:0> a + 1
=> 1
irb(main):003:0> a
=> 0
irb(main):004:0> a = a + 1
=> 1
irb(main):005:0> a
=> 1

no. it matters if you get the return value or assign a value.




Peña schrieb:
> 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.
>
> kind regards -botp
>

Gregor Kopp

8/7/2006 8:26:00 AM

0

Peña schrieb:
> fr joey:
> # Whats wrong with:
> # sum = [1,2,3,4,5].inject{|sum,e| sum+e } ?
>
> dry.


aha, i didnt get the message of fr joey here.
very strange.

Rimantas Liubertas

8/7/2006 8:31:00 AM

0

> 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.

To me sum = [1,2,3,4,5].inject{|sum,e| sum+e } is more DRY

than:
sum =0
[1,2,3,4,5].inject{|sum,e| sum+e }


Regards,
Rimantas
--
http://rim...

Robert Klemme

8/7/2006 9:37:00 AM

0

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

Peña, Botp

8/7/2006 10:02:00 AM

0

fr Robert:
# 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

yes, Robert, that was my most dangerous practice, associating local vars with block vars. I hope to cut the bad practice asap. Ryan just gave a tech explanation, too..

thanks and kind regards -botp