2

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, 100.

Example:

my_array = [
  [[1,  2], [3,   4]],
  [[5,  6], [7,   8]],
  [[9, 10], [11, 12]]
]

my_array.access_using_array([0, 1, 1])
  => 4
0

2 Answers 2

7
[0, 1, 1].inject(my_array, :fetch)
# => 4
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.