Creating and iterating a 2d array in Ruby

45,536

Solution 1

irb(main):001:0> a = []
=> []
irb(main):002:0> a1 = [1, 2]
=> [1, 2]
irb(main):003:0> a2 = [3, 4]
=> [3, 4]
irb(main):004:0> a.push a1             
=> [[1, 2]]
irb(main):005:0> a.push a2
=> [[1, 2], [3, 4]]
irb(main):006:0> a
=> [[1, 2], [3, 4]]
irb(main):007:0> a[0]
=> [1, 2]
irb(main):008:0> a[0][1]
=> 2

Solution 2

a = [[1, 2], [3, 4]]
a.each do |sub|
  sub.each do |int|
    puts int
  end
end
# Output:
#   1
#   2
#   3
#   4

or:

a = [[1, 2], [3, 4]]
a.each do |(x, y)|
  puts x + y
end
# Output:
#   3
#   7

Solution 3

The easiest way to create a 2d array is by the following:

arr1 = Array.new(3) { Array.new(3)}

The code above creates a 2D array with three rows and three columns.

Cheers.

Solution 4

Ruby doesn't have the concept of 2-dimensional arrays like C does. Arrays in Ruby are dynamic -- meaning you can resize them a will. They can contain any object or value in each "slot" - including another Array!

In the examples given by @JunaidKirkire and @simonmenke, you have an array which has arrays for its values. You can access the values using the syntax similar to C - but you could also have the case where one slot is an Array and another is just a number, or a String, or a Hash...

You may want to work through a Ruby tutorial to get a better idea of how it works. I like RubyMonk but there are other good ones out there as well.

Solution 5

Creating a 2d array in Ruby

In ruby, every method accepts a block.

two_d_array = Array.new(3) do
  Array.new(3) do
    0
  end
end

The same can be written In oneline (macro style)

two_d_array = Array.new(3) { Array.new(3) { 0 } }

Output

[
 [0, 0, 0], 
 [0, 0, 0], 
 [0, 0, 0]
]

Iterating a 2d array in Ruby

I can think of three ways.

1: Using range

(0...two_d_array.size).each do |i|
  (0...(two_d_array[i].length)).each do |j|
    puts two_d_array[i][j]
  end
end

2: Using for

for i in (0...two_d_array.size)
 for j in (0...two_d_array[i].length)
  puts two_d_array[i][j]
 end
end

3: Using Each_with_index method

two_d_array.each_with_index do |sub_array, i|
  sub_array.each_with_index do |item, j|
    puts two_d_array[i][j]
  end
end
Share:
45,536
Alex
Author by

Alex

Updated on February 18, 2022

Comments

  • Alex
    Alex over 2 years

    I have very little knowledge about Ruby and cant find a way to create 2d array. Can anyone provide me some snippets or information to get me started?

  • notapatch
    notapatch over 8 years
    Good explanation of creating a 2D array but I does not seem to answer the second part of the question about iterating the 2D array. Currently, the full answer means you should read both this and simonmenke answers - which may be confusing. :)