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?
1
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