Create two-dimensional arrays and access sub-arrays in Ruby Create two-dimensional arrays and access sub-arrays in Ruby ruby ruby

Create two-dimensional arrays and access sub-arrays in Ruby


There are some problems with 2 dimensional Arrays the way you implement them.

a= [[1,2],[3,4]]a[0][2]= 5 # worksa[2][0]= 6 # error

Hash as Array

I prefer to use Hashes for multi dimensional Arrays

a= Hash.newa[[1,2]]= 23a[[5,6]]= 42

This has the advantage, that you don't have to manually create columns or rows. Inserting into hashes is almost O(1), so there is no drawback here, as long as your Hash does not become too big.

You can even set a default value for all not specified elements

a= Hash.new(0)

So now about how to get subarrays

(3..5).to_a.product([2]).collect { |index| a[index] }[2].product((3..5).to_a).collect { |index| a[index] }

(a..b).to_a runs in O(n). Retrieving an element from an Hash is almost O(1), so the collect runs in almost O(n). There is no way to make it faster than O(n), as copying n elements always is O(n).

Hashes can have problems when they are getting too big. So I would think twice about implementing a multidimensional Array like this, if I knew my amount of data is getting big.


rows, cols = x,y  # your valuesgrid = Array.new(rows) { Array.new(cols) }

As for accessing elements, this article is pretty good for step by step way to encapsulate an array in the way you want:

How to ruby array


You didn't state your actual goal, but maybe this can help:

require 'matrix'  # bundled with Rubym = Matrix[ [1, 2, 3], [4, 5, 6]]m.column(0) # ==> Vector[1, 4]

(and Vectors acts like arrays)

or, using a similar notation as you desire:

m.minor(0..1, 2..2) # => Matrix[[3], [6]]