Harry B.
Harry B.

Reputation: 421

What does this array syntax mean in Ruby?

I just came across this code:

@board=Array.new(7){Array.new(7)}

I've never seen this syntax for an array in ruby and I couldn't find much on it after a search. I don't really get what's going on with the curly braces here. I was hoping someone could just give me a brief explanation. Thanks!

Upvotes: 1

Views: 62

Answers (1)

sschuberth
sschuberth

Reputation: 29821

The block-syntax of new allows you to initialize the individual array elements, optionally based on the index number. In your case, the index is not used, but all 7 array elements are initialized with a nested array of also 7 elements, so you get a 7x7 "matrix".

To illustrate:

$ irb
irb(main):001:0> Array.new(7)
=> [nil, nil, nil, nil, nil, nil, nil]

$ irb
irb(main):001:0> require 'pp'
=> true
irb(main):002:0> pp Array.new(7) {Array.new(7)}
[[nil, nil, nil, nil, nil, nil, nil],
 [nil, nil, nil, nil, nil, nil, nil],
 [nil, nil, nil, nil, nil, nil, nil],
 [nil, nil, nil, nil, nil, nil, nil],
 [nil, nil, nil, nil, nil, nil, nil],
 [nil, nil, nil, nil, nil, nil, nil],
 [nil, nil, nil, nil, nil, nil, nil]]

Upvotes: 3

Related Questions