Stefano Crocco
10/17/2007 11:51:00 AM
Alle mercoledì 17 ottobre 2007, Shuaib Zahda ha scritto:
> Dear all
>
> I worked for quite some hours and i googled the two dimensional array in
> ruby and yet my problem is partially solved
>
> I want to declare 2-dimensional arrays it has 6 columns but uknow number
> of columns.
> i tried this way
> array = [][] # did not work
> array = [[],[]] # it works but only for two elements.
>
> another question I believe the answer is no but i want to confirm
> can we have multi-dimensional hash? :)
>
> any one has any idea to share
> Regards
> Shuaib
Ruby doesn't have 2-dimensional arrays, but you can use nested arrays to
achieve the same effect. If you want an array with 6 columns and any number
of rows, you can do something like:
a = Array.new(6){[]}
This creates an array of 6 elements, each of one contains an array. Each
element represents a column. The entries of the column are stored into the
nested array.
You can store entries like this:
a[2][3] = 1
This sets the element 3 of the row 2 to be one.
Of course, this approach allows you to have columns with different sizes. For
example, since each clumn is an array, you can do this:
a[1] << 2
This increases the size of the column 1 by one, by appending an element to it.
If you want to avoid this, you can wrap the 2d array in a class:
class Array2D
def initialize cols, default = nil
@data = Array.new(cols){[]}
@default = default
end
def append_row
@data.each{|c| c << @default}
end
def [](col, row=nil)
if row then @data[col][row]
else @data[col].dup
end
end
def []=(col, row, value)
raise IndexError if col >= @data.size or row >= @data[0].size
@data[col][row]=value
end
def each_col
@data.each{|c| yield c.dup}
end
def each
@data.each do |c|
c.each{|i| yield i}
end
end
end
USAGE:
a = Array2D.new 3, :a
3.times{a.append_row}
a[0, 0] = :b
a[1, 2] = :c
p a[0]
p a[1]
p a[2]
Regarding your second question, what do you mean by "multidimensional hash"?
Stefano