Multiple array declaration using one Object::new call


I apologize if this has been covered, but I searched and could not find
anything resembling this issue. I am fairly new to Ruby and I’m having
a strange problem that may be my misunderstanding of how Ruby works.

I am trying to declare multiple arrays on one line, like such:

array1, array2, array = Array::new()

What happens is that the arrays are all nil and [seemingly] immutable.

When I declare each array individually, like such:

array1 = Array::new()
array2 = Array:new()
array3 = Array::new()

…the arrays are not nil and mutable (as verified with irb).

When I do this with a set of strings, like such:

str1, str2, str3 = String::new()

…str1 is not nil, but str2 and str 3 are nil.

Can someone shed some light on what I’m misunderstanding, and perhaps
guide me to a good source on proper object declarations?


On Aug 4, 2011, at 1:42 PM, Andy D. wrote:

What happens is that the arrays are all nil and [seemingly] immutable.
This is a part of ruby that can trip us all up at times. What you’re
here is implicit array expansion on the right-hand side. It’s easiest to
illustrate with a motivating example:

a, b, c = [1, 2, 3]

On the left-hand side, we have 3 variables, and on the right-hand side,
have 1 value. The value on the right is an Array, so it is expanded into

a, b, c = 1, 2, 3

If the array isn’t big enough to satisfy all the left-hand side
variables, it puts
“nil” in the expanded assignment:

a, b, c = [1, 2]


a, b, c = 1, 2, nil

What you’ve got is equivalent to this:

a, b, c = [ ]

which becomes:

a, b, c = nil, nil, nil

by the same rule as above.

For a more precisely-worded explanation of all this, see “Read Ruby”, a
nice online manual for Ruby 1.9:

Michael E.
[email protected]

Michael – thank you for the clear explanation and the online manual
reference. I sensed it was something I was doing wrong… and I was
right! Best regards, Andy.