2009-11-12 97 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