2009-11-12 81 views
0

我需要创建一个二维阵列类。我已经做了工作,但发现我的类只具有一个内部的两维数组,以及访问我必须写一冗词“表”的元素:红宝石:OOP&两维数组问题

class Table 
    attr_accessor :table 
    def initialize(w,h) 
    @table = Array.new(h) 
    h.times do @table << Array.new(w) 
    end 
end 

x = Table.new(10,10) 
x.table[5][6] = 'example' 

等。这个想法是,我只想x[5][6]一次写访问的元素。据我所知,我必须继承Array类,并以某种方式扩展它以表现为双暗数组。如果我是对的 - 我该怎么做?

回答

1

认为这可能是你在找什么。它使用@table实例变量来跟踪内部数组,但不公开的访问它。这里的定义是:

class Table 

    def initialize(row_count, column_count) 
    @table = Array.new 

    row_count.times do |index| 
     @table[index] = Array.new(column_count) 
    end 
    end 

    def []=(row, column, value) 
    @table[row][column] = value 
    end 

    def [](row, column = nil) 
    if column.nil? 
     @table[row] 
    else 
     @table[row][column] 
    end 
    end 

    def inspect 
    @table.inspect 
    end 
end 

下面是如何使用它:

t = Table.new(2, 5) 
t[0,0] = 'first' 
t[1,4] = 'last' 
t[0][1] = 'second' 

puts t[0,0] 
puts t.inspect 

你可能也想看看Ruby's enumerable module而非继承阵列。

0

有你想编写自己的数组类的任何具体原因是什么?默认情况下,你可以告诉数组做什么用填充新的元素,通过提供第二个参数:

>> a = Array.new(10, []) 
=> [[], [], [], [], [], [], [], [], [], []] 

编辑:很显然,这种方式填充阵列,以传递的对象引用,所以一旦你做a[0][0] = "asd",包含数组的每个第一个元素都会改变。不酷。

>> a[0][0] = "asd" 
=> "asd" 
>> a 
=> [["asd"], ["asd"], ["asd"], ["asd"], ["asd"], ["asd"], ["asd"], ["asd"], ["asd"], ["asd"]] 

要具有各自包含阵列是唯一的,使用第三语法,并给它一个块中的每个的执行时间 - 块的结果将被用于填充阵列:

>> b = Array.new(10) { [] } 
=> [[], [], [], [], [], [], [], [], [], []] 
>> b[0][0] = "asd" 
=> "asd" 
>> b 
=> [["asd"], [], [], [], [], [], [], [], [], []] 

另外,由于道路红宝石阵列工作,定义y轴的尺寸甚至没有必要的:当你把东西比当前的大小更大指数

>> a = Array.new(5) 
=> [nil, nil, nil, nil, nil] 
>> a[10] 
=> nil 
>> a[10] = "asd" 
=> "asd" 
>> a 
=> [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, "asd"] 

阵列自动扩展。所以,只需创建一个包含10个空数组的数组,并且您有10 * n大小的数组即可使用。

+0

呀,我真的想创建一个类来分开它从实际算法的逻辑,其上我现在的工作路线内(即方法)。感谢阵列自动调整大小!不知道 – gmile 2009-11-12 09:42:27