Ruby Inject

Weird behavior of inject() method in Ruby:

fruits = %w{apples oranges bananas}

str = “”
fruits.inject { |str, x| str << x }
p str
p fruits

Produces:

“applesorangesbananas”   # Correct
[“applesorangesbananas”, “oranges”, “bananas”]   # Wrong

Why did it modify the original array? The inject should only be working on str.

To produce the desired result, I had to replace the inject() with inject(“”).

But works correctly, as you’d expect it to, when using an array of integers:

n = [1, 2, 3, 4]

sum = 0
n.inject { |sum, i| sum += i }
p sum
p n

Correctly produces:

10  # Correct
[1, 2, 3, 4]  # Correct

# Works as should, array n does not get modified.