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]
]
Ursus
  • 29,643
  • 3
  • 33
  • 50
Eduard
  • 61
  • 4
  • Sorry, I changed your array that was not a valid array – Ursus Nov 11 '20 at 22:43
  • Does this answer your question? [How do I assign default values for two-dimensional array?](https://stackoverflow.com/questions/20599437/how-do-i-assign-default-values-for-two-dimensional-array) – pjs Nov 11 '20 at 22:56

1 Answers1

3

Sure

Array.new(3) { Array.new(4, 0) }
 => [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] 
Ursus
  • 29,643
  • 3
  • 33
  • 50
  • 2
    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](https://ruby-doc.org/core-2.7.0/Array.html#method-c-new). – Cary Swoveland Nov 12 '20 at 00:43
  • @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. – user1934428 Nov 12 '20 at 07:33
  • 1
    @CarySwoveland putting `0` in an extra block is superfluous because integers are immutable. Ursus' answer is perfectly fine. – Stefan Nov 12 '20 at 07:59
  • Yeah, obviously I tried and there is no need for the extra block – Ursus Nov 12 '20 at 08:31
  • 1
    @Stefan and Ursus, I was not advocating the variant; I mentioned it only to alert Eduard in case he saw it written that way. – Cary Swoveland Nov 12 '20 at 16:16
  • Someone took it that way because I've received a downvote :D – Ursus Nov 12 '20 at 16:18