Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
有没有办法使用本身存储在数组中的索引来动态访问嵌套数组?
主数组/矩阵嵌套可以是可变的,例如 2、4、100。
例子:
my_array = [ [[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]] ] my_array.access_using_array([0, 1, 1]) => 4
[0, 1, 1].inject(my_array, :fetch) # => 4
Ruby 2.3.0 引入了一种在两者上调用的新方法digHash,Array从而解决了这个问题。
dig
Hash
Array
nil如果在任何级别的嵌套中缺少元素,它就会返回。
nil
my_array.dig(0,1,1)