2017-10-05 63 views
-2

我想實現一個表數據結構。也許你可以推薦一個更好的選擇,但由於Ruby沒有提供多維數組的內置支持,最近的解決方案是使用Hash和數組作爲指數多維紅寶石數組:是否可以使用多個參數定義[] -operator?

pseudoTable = Hash.new 
pseudoTable[[0,"id"]] = 23 
pseudoTable[[0,"name"]] = "Hans" 

現在我嘗試以下

class MyTable 
    attr_accessor :id, :table_hash 
    def [](a,b) 
    @table_hash[[a,b]] 
    end 
end 

那麼,在Ruby中不可能給出兩個參數給def []()

如果不是的話,你能否推薦另一種方法(內置數據結構比哈希等更適合)來實現一個能夠按順序迭代的動態擴展和獎勵點表?

+3

_「是不是有可能在Ruby中給兩個參數變形點焊[] ()?「 - - 你剛剛做到了。有沒有錯誤或什麼? – Stefan

+1

我認爲這是https://stackoverflow.com/questions/7014052/ruby-multidimensional-array – Hirurg103

回答

3

這是您要查找的行爲嗎?

class MyTable 
    def initialize() 
    @table = Hash.new 
    end 

    def [](a, b) 
    return nil if @table[a].nil? 
    @table[a][b] 
    end 

    def []=(a, b, c) 
    @table[a] ||= {} 
    @table[a][b] = c 
    end 
end 

用法:

2.4.1 :038 > a = MyTable.new 
=> #<MyTable:0x007faf6f9161c8 @table={}> 
2.4.1 :039 > a[0,0] 
=> nil 
2.4.1 :040 > a[0,0] = 1 
=> 1 
2.4.1 :041 > a[0,0] 
=> 1 

我很有信心有更好的方法來做到這一點,這種解決方案可能包含了一些錯誤,但希望它演示瞭如何定義和使用的多參數[][]=方法。

+0

我認爲這是一個很好的通用示例,並且會幫助很多人。 –

+0

是否還有其他內置數據結構可能比Hashes更適合並且允許順序迭代? –

+1

好的答案,請注意,你可以在近期版本的ruby中使用'dig'來在'[]'方法中繞過nil的測試...'def [](a,b); @ table.dig(a,二); end' – SteveTurczyn

1

你做了什麼可以正常工作,麻煩的是@table_hash不被識別爲散列。你需要初始化它。

class MyTable 
    attr_accessor :id, :table_hash 

    def initialize(*args) 
    @table_hash = Hash.new 
    super 
    end 

    def [](a,b) 
    @table_hash[[a,b]] 
    end 
end 
+0

的重複你是對的。沒有錯誤。 我真的不知道出了什麼問題。對不起,你有這樣的打擊我的煩惱。我確定我已經將它初始化爲Hash.new。 感謝您的回答斯蒂芬和史蒂夫! 您好, von Spotz –

1

你可以嘗試使用ruby-numo library

apt install -y git ruby gcc ruby-dev rake make 
gem install specific_install 
gem specific_install https://github.com/ruby-numo/narray.git 

irb 

arr = Numo::Narray[[1], [1, 2], [1, 2, 3]] 

=> Numo::Int32#shape=[3,3] 
[[1, 0, 0], 
[1, 2, 0], 
[1, 2, 3]] 

arr[0, 0] 
=> 1 

arr[0, 1] 
=> 0 

arr[0, 2] 
=> 0 

arr[0, 3] 
IndexError: index=3 out of shape[1]=3  

您可以瞭解更詳細的文檔there