[英]Multidimensional ruby array: Is it possible to define the []-operator with more than one argument?
我想實現一個表數據結構。 也許您可以推薦一個更好的替代方案,但由於 Ruby 不提供對多維數組的內置支持,因此最近的解決方案是使用 Hash 和 Array 作為索引
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 []()
提供兩個參數?
如果沒有,您能否推薦另一種方法(比 Hash 更適合的內置數據結構等)來實現一個能夠動態擴展的表和順序迭代的獎勵積分?
這是您正在尋找的行為嗎?
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
我非常有信心有更好的方法來做到這一點,這個解決方案可能包含一些錯誤,但希望它展示了如何定義和使用多參數[]
和[]=
方法。
您可以嘗試使用ruby-numo 庫
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
您可以在那里了解更詳細的文檔
你所做的會正常工作,問題是@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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.