1

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!

5
  • 1
    Read the documentation here: ruby-doc.org/core-2.2.0/Array.html#method-c-new Commented Jul 1, 2016 at 14:44
  • I understand in the documentation when they use an example with a hash. I'm assuming this just makes a 2-d array, but I guess I just don't understand why. Commented Jul 1, 2016 at 14:47
  • It clear says ...In the last form, an array of the given size is created. Each element in this array is created by passing the element’s index to the given block and storing the return value. - what it means is that when you access any index of @board, it will be an array of 7 elements - yes its a way to create a 2D array. Commented Jul 1, 2016 at 14:51
  • okay, thank you for your help. Commented Jul 1, 2016 at 14:52
  • Your question is unclear. Which part of the syntax exactly do you not understand? There are only 5 syntactic constructs in the code you posted: message sends, variable dereferences, integer literals, a block, and an assignment. Which of the 5 are you asking about? Commented Jul 3, 2016 at 21:45

1 Answer 1

3

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]]
Sign up to request clarification or add additional context in comments.

2 Comments

Okay, that makes more sense to me now. I didn't really understand what was going on under the hood I guess. Thanks!
@HarryB. Consider accepting this answer, unless you're waiting for more answers: stackoverflow.com/help/someone-answers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.