Archive

Archive for June, 2007

Inject Bug?

June 21, 2007 Pari Leave a comment

Is this a bug??

fruits = %w{apples oranges bananas}

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

Produces:

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

Not only is the first element of the array fruits wrong, the it shouldn’t even get modified! The inject should only be working on str.

To produce the desired result, I had to replace the inject() with inject(“”). Though, still I don’t agree with the behavior – inject should not modify the source array, it should have modified only str.

For example, this code:

n = [1, 2, 3, 4]

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

Correctly produces:

10
[1, 2, 3, 4]

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

Categories: Coding