【问题标题】:Multidimensional ruby array: Is it possible to define the []-operator with more than one argument?多维 ruby​​ 数组:是否可以使用多个参数定义 [] 运算符?
【发布时间】:2018-03-16 19:54:23
【问题描述】:

我想实现一个表数据结构。也许你可以推荐一个更好的替代方案,但是由于 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 等更适合的内置数据结构)来实现一个能够动态扩展的表并获得可顺序迭代的奖励积分?

【问题讨论】:

标签: arrays ruby multidimensional-array


【解决方案1】:

这是您要寻找的行为吗?

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​​ 中使用 dig 来绕过 [] 方法中的 nil 测试...def[](a,b);@table.dig(a, b);end
【解决方案2】:

你可以尝试使用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

【讨论】:

    【解决方案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
    

    【讨论】:

    • 你是对的。没有错误。我真的不知道出了什么问题。很抱歉让您为我的这种失误而烦恼。我确定我已将其初始化为 Hash.new。感谢您的回答 Stefan 和 Steve!此致,冯·斯波茨
    猜你喜欢
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2020-03-03
    • 2010-12-16
    相关资源
    最近更新 更多