There are some problems with the 2-dimensional Arrays way to implement them.
a= [[1,2],[3,4]] a[0][2]= 5 # works a[2][0]= 6 # error
Hash like Array
I prefer to use Hashes for multidimensional Arrays
a= Hash.new a[[1,2]]= 23 a[[5,6]]= 42
This has the advantage that you do not need to manually create columns or rows. The hash insert is almost O (1) , so there is no shortage here if your Hash does not get too big.
You can even set a default value for all items not specified
a= Hash.new(0)
So, now on 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 works in O (n). Getting an element from Hash is almost O (1), so the collection is done in almost O (n). It is impossible to do this faster than O (n), since copying n elements is always equal to O (n).
Hashes can have problems when they get too big. So I would think twice about implementing a multidimensional Array , like this, if I knew that my data volume was becoming large.
johannes Nov 12 '09 at 11:54 2009-11-12 11:54
source share