[英]Multidimensional ruby array: Is it possible to define the []-operator with more than one argument?
I want to implement a table datastructure.我想实现一个表数据结构。 Maybe you can recommend a better alternative, but as Ruby doesn't provide built-in support for multidimensional arrays, the nearest solution is using a Hash and an Array as index
也许您可以推荐一个更好的替代方案,但由于 Ruby 不提供对多维数组的内置支持,因此最近的解决方案是使用 Hash 和 Array 作为索引
pseudoTable = Hash.new
pseudoTable[[0,"id"]] = 23
pseudoTable[[0,"name"]] = "Hans"
Now I tried the following现在我尝试了以下
class MyTable
attr_accessor :id, :table_hash
def [](a,b)
@table_hash[[a,b]]
end
end
So, isn't it possible in Ruby to give two arguments to def []()
?那么,在 Ruby 中是否可以为
def []()
提供两个参数?
If not, can you recommend another approach (a built-in datastructure than Hash, etc. better suited) to implement a table capable of dynamic extension and bonus points for being sequentially iterable?如果没有,您能否推荐另一种方法(比 Hash 更适合的内置数据结构等)来实现一个能够动态扩展的表和顺序迭代的奖励积分?
Is this the behavior you're looking for?这是您正在寻找的行为吗?
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
usage:用法:
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
I'm pretty confident there are better ways to do this, and this solution might contain some bugs, but hopefully it demonstrates how to define and use multi-argument []
and []=
methods.我非常有信心有更好的方法来做到这一点,这个解决方案可能包含一些错误,但希望它展示了如何定义和使用多参数
[]
和[]=
方法。
You can try to use ruby-numo library您可以尝试使用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
You can learn more detailed documentation there您可以在那里了解更详细的文档
What you did would work fine, the trouble is that @table_hash
is not recognised as a hash.你所做的会正常工作,问题是
@table_hash
不被识别为哈希。 You need to initialize it as such.您需要像这样初始化它。
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.