Destructuring arrays in enumerable requires array of arrays

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the ruby category.

Last Updated: 2024-10-12

I had data akin to the following

triples = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

I wanted the 2nd element of each array, so I tried the following:

triples.first.map {|a,b,c| b}

This failed, in that b was equal to nil. When I switched it to a, it contained the entire triplet.

The error occurred because I switched type from an array of arrays, to a single array by calling first. Thus the code was mapping over the elements in the array [1, 2, 3] and therefore only had one variable to assign, a.

The fix was to keep things as an array of arrays all the way

triples.first(2).map {|a,b,c| b}