There are some problems with 2 dimensional Arrays
the way you implement them.
a= [[1,2],[3,4]]
a[0][2]= 5 # works
a[2][0]= 6 # error
Hash
as Array
I prefer to use Hash
's for multi dimensional Array
's
a= Hash.new
a[[1,2]]= 23
a[[5,6]]= 42
This has the advantage, that you don't have to manually create collumns or rows. Inserting into hashes is almost O(1), so there is no drawback here, as long as your Hash
does not bekome to big.
You can even set a default value for all not specified elements
a= Hash.new(0)
So now about how to get subarray's
(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 now way to make it faster than O(n), as copying n elements always is O(n).
Hash
's can have problems when they are getting to big. So I would think twice about implementing a multidimensional Array
like this, if I knew my amount of data is getting big.