Ruby array += vs push

Viewed 4002

I have an array of arrays and want to append elements to the sub-arrays. += does what I want, but I'd like to understand why push does not.

Behavior I expect (and works with +=):

b = Array.new(3,[])
b[0] += ["apple"]
b[1] += ["orange"]
b[2] += ["frog"]

b => [["apple"], ["orange"], ["frog"]]

With push I get the pushed element appended to EACH sub-array (why?):

a = Array.new(3,[])
a[0].push("apple")
a[1].push("orange")
a[2].push("frog")

a => [["apple", "orange", "frog"], ["apple", "orange", "frog"], ["apple", "orange", "frog"]]

Any help on this much appreciated.

2 Answers
Related