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.
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.
# 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 "--" end10 20 30 -- 40 50 60 --
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()
.
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 "--" endThird element in first row is: 3 1 2 3 -- 10 500 30 --
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.
# 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 end0 0... A 0 1... B 0 2... C 1 0... D 1 1... E 1 2... F 2 0... G 2 1... H
A 2D array has depth. A flat array is one-dimensional. With flatten, and "flatten!" we convert a multidimensional array into a flat one.
gems = [["ruby", 10], ["sapphire", 20]] p gems # Call flatten to change a 2D array into one dimension. gems.flatten! p gems[["ruby", 10], ["sapphire", 20]] ["ruby", 10, "sapphire", 20]
In Ruby we compose two-dimensional arrays by nesting Arrays. This also gives us the ability to create jagged (uneven) arrays.
With each and each_index
, we iterate over nested collections. With flatten, we have a method that changes nested arrays into linear ones.