Map array of ints to nested array access

前端 未结 2 1901
青春惊慌失措
青春惊慌失措 2021-01-15 00:09

Is there a way to dynamically access a nested array using indices which are themselves stored in an array?

The main array/matrix nesting could be variable e.g. 2, 4,

相关标签:
2条回答
  • 2021-01-15 00:27

    Ruby 2.3.0 introduced a new method called dig on both Hash and Array that solves this problem.

    It returns nil if an element is missing at any level of nesting.

    my_array.dig(0,1,1)
    
    0 讨论(0)
  • 2021-01-15 00:41
    [0, 1, 1].inject(my_array, :fetch)
    # => 4
    
    0 讨论(0)
提交回复
热议问题