Multi-dimensional arrays

G

Graham Smith

Hi,

I have just started programming with Ruby and have run into the following
problem.

I'm trying to work with 3 dimensional arrays and have run into a problem
dimensioning the array.

a = [[[]]]
a[0][0] = [ 0,1,2,3]
a[0][1] = [ "zero", "one","two",three"]

The above assignments work without a problem, but the following assignment
fails.

a[1][0] = [ 4, 5, 6, 7]
NoMethodError: undefined method `[]=' for nil:NilClass

How do you dimension the number of elements in a multi-dimensional array when
the final number of elements in the array is not known.
 
L

Logan Capaldo

Hi,

I have just started programming with Ruby and have run into the
following
problem.

I'm trying to work with 3 dimensional arrays and have run into a
problem
dimensioning the array.

a = [[[]]]
a[0][0] = [ 0,1,2,3]
a[0][1] = [ "zero", "one","two",three"]

The above assignments work without a problem, but the following
assignment
fails.

a[1][0] = [ 4, 5, 6, 7]
NoMethodError: undefined method `[]=' for nil:NilClass

How do you dimension the number of elements in a multi-dimensional
array when
the final number of elements in the array is not known.

class Array
def default(&proc)
@default = proc
self
end

alias_method :rb_array_indexing, :"[]"
def [](index)
if @default and index.kind_of? Integer and index >= length
index.downto(length) do |i|
self = @default.call(i)
end
end
rb_array_indexing(index)
end
end

a = []
a.default { [] }

a[1][0] = "Hello"
a #=> [[], ["Hello"]]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,816
Latest member
SapanaCarpetStudio

Latest Threads

Top