0

Without using index I was able to destructure the first and second elements of an Array of Arrays like so:

[ [ 1, 2 ], [ 3, 4 ] ].each do |first, second|
  puts second
end
#=> 2
#=> 4

I then needed to get the index for each iteration so I used .with_index and I assumed the index would just get added as the last argument of the block:

[ [ 1, 2 ], [ 3, 4 ] ].each.with_index do |first, second, index|
  puts second
end
#=> 0
#=> 1

However, it was the index. The first value is the entire Array, not destructured.

How do you use .with_index and still destructure the Array?

2

1 Answer 1

4

You can destructure by passing parentheses to the first argument and that will destructure as before and keep the index as the second argument:

[ [ 1, 2 ], [ 3, 4 ] ].each.with_index do |( first, second ), index|
  puts second
end
#=> 2
#=> 4
Sign up to request clarification or add additional context in comments.

1 Comment

Just as (first, second), idx = [[[1,2], [3,4]], 2] produces first #=> [1,2], second #=> [3,4], idx #=> 2. See the doc for Array Decomposition.

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.