TheDeveloperBlog.com


Ruby 2D Array Examples

2D arrays. Often data is two-dimensional. We need to access cells by rows and columns. With the Array in Ruby, we can nest Arrays, creating 2D arrays.


With nested iterators, we loop over elements. And with built-in methods like flatten() we can transform nested arrays into 1-dimensional ones.


First example. Here we use an Array initialization statement to create a 2D array in one line. We then use the each iterator to loop over rows.

Finally: We invoke the each iterator to process the individual cells in the nested arrays.

Based on:

Ruby 2

Ruby program that uses 2D array

# This 2D array contains two sub-arrays.
values = Array[[10, 20, 30], [40, 50, 60]]

# Loop over each row array.
values.each do |x|

    # Loop over each cell in the row.
    x.each do |cell|
	puts cell
    end

    # End of row.
    puts "--"
end

Output

10
20
30
--
40
50
60
--

Push. Here we create nested Arrays with push method calls. We create an empty Array and then create a subarray. We add three elements to it with push().

Lookup: We can look up the element in a 2D array by accessing first the row and then the column of the cell.

Ruby program that uses 2D array, push

values = []

# Create first row.
subarray = []
subarray.push(1)
subarray.push(2)
subarray.push(3)

# Add first row.
values.push(subarray)

# Create second row.
subarray = []
subarray.push(10)
subarray.push(20)
subarray.push(30)

# Add second row.
values.push(subarray)

# Load an element.
puts "Third element in first row is: " << String(values[0][2])

# Change this element.
values[1][1] = 500

# Display all elements.
values.each do |x|
    x.each do |y|
	puts y
    end
    puts "--"
end

Output

Third element in first row is: 3
1
2
3
--
10
500
30
--

Indexes. Next we show how to access each cell in a 2D array by indexes. We use the each_index iterator on rows, and then call it again on each row.

Coordinates: We then access each cell value using the two coordinates from the iterators.

Tip: This style of code also handles uneven, jagged arrays—we get a different maximum row index for each row.

Ruby program that uses each_index

# This is an irregular 2D array (a jagged array).
values = [["A", "B", "C"], ["D", "E", "F"], ["G", "H"]]

# Loop over indexes.
values.each_index do |i|

    # Get subarray and loop over its indexes also.
    subarray = values[i]
    subarray.each_index do |x|
	# Display the cell.
	puts String(i) << " " << String(x) << "... " << values[i][x]
    end

end

Output

0 0... A
0 1... B
0 2... C
1 0... D
1 1... E
1 2... F
2 0... G
2 1... H

Flatten. A 2D array has depth. A flat array is one-dimensional. With flatten, and "flatten!" we convert a multidimensional array into a flat one.

Tip: This method works recursively. Even heavily nested arrays (3-dimensional, 4-dimensional ones) are flattened.

Ruby program that uses flatten method

gems = [["ruby", 10], ["sapphire", 20]]
p gems

# Call flatten to change a 2D array into one dimension.
gems.flatten!
p gems

Output

[["ruby", 10], ["sapphire", 20]]
["ruby", 10, "sapphire", 20]

A summary. In Ruby we compose two-dimensional arrays by nesting Arrays. This also gives us the ability to create jagged (uneven) arrays.


Features. With each and each_index, we iterate over nested collections. With flatten, we have a method that changes nested arrays into linear ones.