<< Back to RUBY
Ruby 2D Array Examples
Use 2D arrays and jagged arrays. Nest arrays and access subarrays.2D array. 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.
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.
Related Links:
- Ruby Convert Types: Arrays and Strings
- Ruby File Handling: File and IO Classes
- Ruby Regexp Match Method
- Ruby String Array Examples
- Ruby include: Array Contains Method
- Ruby Class Examples: Self, Super and Module
- Ruby DateTime Examples: require date
- Ruby 2D Array Examples
- Ruby Number Examples: Integer, Float, zero and eql
- Ruby Exception Examples: Begin and Rescue
- Top 65 Ruby Interview Questions (2021)
- Ruby on Rails Interview Questions (2021)
- Ruby String Examples (each char, each line)
- Ruby if Examples: elsif, else and unless
- Ruby Math Examples: floor, ceil, round and truncate
- Ruby Sub, gsub: Replace String
- Ruby Substring Examples
- Ruby Console: Puts, Print and stdin
- Ruby Remove Duplicates From Array
- Ruby Random Number Generator: rand, srand
- Ruby Recursion Example
- Ruby ROT13 Method
- Ruby Iterator: times, step Loops
- Ruby String Length, For Loop Over Chars
- Ruby Join Example (Convert Array to String)
- Ruby Format String Examples
- Ruby Copy Array Example
- Ruby Keywords
- Ruby Nil Value Examples: NoMethodError
- Learn Ruby Tutorial
- Ruby Method: Def, Arguments and Return Values
- Ruby Fibonacci Sequence Example
- Ruby Hash Examples
- Ruby While, Until and For Loop Examples
- Learn Ruby on Rails Tutorial
- Ruby Word Count: Split Method
- Ruby Sort Arrays (Use Block Syntax)
- Ruby Case Examples: Ranges, Strings and Regexp
- Ruby Array Examples
- Ruby Split String Examples
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf