Home>

I have a question about defining multiple empty arrays in Ruby.

I know that multiple assignments can assign values ​​to multiple variables at once,
I don't know how to define an empty array for multiple variables at once.

In the code below, each variable seems to containnil.

a, b, c, d = []

You can define an empty array for each variable with the following code,
It seems like a redundant way of writing.
I want to express this in one line.

a = []
b = []
c = []
d = []
  • Answer # 1

    You can do either of the following:

    a = b = c = d = [] # This will all refer to the same object
    a, b, c, d = [], [], [], []
    # I really want to do DRY
    a, b, c, d = Array.new (4) .map {[]}

  • Answer # 2

    a, b, c, d = [[]]*Four
    p a, b, c, d

    Add a comment

    a, b, c, d = Array.new (4) {[]}
    p a, b, c, d
    a<<1
    p a, b, c, d