Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Enumerable

About array inject

You specify about array inject

array = [1,2,3,4,5,6] array.inject {|sum, element| sum =+ element}

will return the sum of all elements in the array because the variable sum is kept between iterations and on the next itiration sum is added again with its previous value to the current element

This is fine.

But why does this work as well?

array.inject {|sum, element| sum + element}

Here we are not storing the result of sum + element in the sum variable but it somehow still returns the correct value?

Why?

1 Answer

Both work. The block you pass into inject expects you to return a value, and it doesn't matter if you modify it in place. But, remember that sum += element returns sum + element as well as modifying in place the value of sum. Therefore, their return values are equivalent, and the return value is returned from the block. I'm not sure why Jason used += instead of +, because the first one is much more confusing (are you trying to modify in place??)