1

For example, initialize the entire array to 0 or any other value.

[
  [0, 0, 0, 0],
  [0, 0, 0, 0], 
  [0, 0, 0, 0]
]
2

1 Answer 1

3

Sure

Array.new(3) { Array.new(4, 0) }
 => [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] 
Sign up to request clarification or add additional context in comments.

6 Comments

Eduard, a variant of this answer is Array.new(3) { Array.new(4) { 0 } }. You need to understand that this answer is not the same as arr = Array.new(3, Array.new(4, 0)) #=> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]. The latter would be incorrect, for if we set arr[0][0] = 1 we would find arr #=> [[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]. See Array::new.
@CarySwoveland : May I suggest thta you post this as answer instead of a comment, because this seems to really be the anwer to the OPs problem.
@CarySwoveland putting 0 in an extra block is superfluous because integers are immutable. Ursus' answer is perfectly fine.
Yeah, obviously I tried and there is no need for the extra block
@Stefan and Ursus, I was not advocating the variant; I mentioned it only to alert Eduard in case he saw it written that way.
|

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.