Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby inject function

Tags:

ruby

Why does the second one not return the same value as the first?

puts (3..5).map{|n| n**3}.inject{|sum,n| sum + n}
puts (3..5).inject{|sum,n| sum + n**3}

216 192

like image 417
Jeff Avatar asked Aug 06 '13 11:08

Jeff


1 Answers

Because in the first case the starting value of the accumulator is 27, in the second case it is 3.

If you use 0 as an explicit starting value, both will evaluate to the same number:

(3..5).map {|n| n**3 }.inject(0) {|sum,n| sum + n }
# => 216
# or just
(3..5).map {|n| n**3 }.inject(0, :+)

(3..5).inject(0) {|sum,n| sum + n**3 }
# => 216
like image 144
Jörg W Mittag Avatar answered Sep 28 '22 07:09

Jörg W Mittag