In Ruby, with a 1D Array, I can dynamically select elements by passing an Integer key in brackets, as follows:
example = [0,1,2,[3,4]]
i = 2
example[i]
==> 2
What I would like to achieve, is to dynamically update an element in a multi-dimensional Array by passing an Array of Integers, each representing the index to select in each array. Example of what I'd like to achieve:
example = [0,1,2,[3,4]]
path = [3, 1] (corresponds to the 4)
example[*path or some other syntax] = 9
example
==> [0,1,2,[3,9]]
What I've tried is storing the result with each path iteration:
temp = example
path.each {|index|
temp = temp[index]
}
temp
==> 4
This successfully identifies the element I'd like to update. However, it appears to have stored a copy, rather than to reference the original location, as:
temp = 9
example
==> [0,1,2,[3,4]]
How can I update the base array example without hardcoding path in individual brackets?
Clarification after a comment: I don't know the path length in advance, which is why hardcoding isn't viable.
example[3][1] = 9isn't enough?pathlengths. Hard-coding with brackets limits me to a 2-steppath.