繁体   English   中英

多维 ruby​​ 数组:是否可以用多个参数定义 [] 运算符?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM