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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With