2017-10-05 61 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