Today I Learned

hashrocket A Hashrocket project

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"
See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.