How to Create a Ruby Two-Dimensional Array

09/23/2021

Contents

In this article, you will learn how to create a Ruby two-dimensional array.

Creating a Ruby two-dimensional array

To create a Ruby two-dimensional array, you can use the Array.new method and pass in the size of the array as the first argument, followed by a block that returns a new array. Here’s an example:

# create a 2D array with 3 rows and 4 columns
arr = Array.new(3) { Array.new(4, 0) }

# set the value at row 1, column 2 to 5
arr[1][2] = 5

# print the array
p arr
# Output: [[0, 0, 0, 0], [0, 0, 5, 0], [0, 0, 0, 0]]

In this example, we’re creating a 2D array with 3 rows and 4 columns, initialized with zeros. We’re using the Array.new method to create a new array with 3 elements, and passing in a block that returns a new array with 4 elements, all initialized to 0.

To access a specific element in the 2D array, we use the index operator twice, once to access the row and another to access the column.

Alternatively, you can also create a 2D array using the bracket syntax. Here’s an example:

# create a 2D array with 3 rows and 4 columns
arr = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

# set the value at row 1, column 2 to 5
arr[1][2] = 5

# print the array
p arr
# Output: [[0, 0, 0, 0], [0, 0, 5, 0], [0, 0, 0, 0]]

In this example, we’re creating a 2D array with 3 rows and 4 columns using the bracket syntax. We’re then accessing the element at row 1, column 2 and setting it to 5.

Both of these methods allow you to create and manipulate 2D arrays in Ruby, depending on your preference and use case.