Decomposing Nested Arrays
As you probably already know, in Ruby, you can decompose a nested array into variables like so:
letters_and_numbers = [["a", "b", "c", "d", "e"], [1, 2, 3, 4, 5]]
letters, numbers = letters_and_numbers
>> letters
=> ["a", "b", "c", "d", "e"]
>> numbers
=> [1, 2, 3, 4, 5]
However, did you also know that you can add parentheses ()
to decompose specific values from a nested array?
letters_and_numbers = [["a", "b", "c", "d", "e"], [1, 2, 3, 4, 5]]
(a, b, *other_letters), numbers = letters_and_numbers
>> a
=> "a"
>> b
=> "b"
>> other_letters
=> ["c", "d", "e"]
>> numbers
=> [1, 2, 3, 4, 5]
Note: You can also grab values from either the beginning or end of the array!
letters_and_numbers = [["a", "b", "c", "d", "e"], [1, 2, 3, 4, 5]]
(a, *other, d, e), _ = letters_and_numbers
>> a
=> "a"
>> other
=> ["b", "c"]
>> d
=> "d"
>> e
=> "e"
Tweet