1 min read

TIL: Denaturing Ruby Array to get the Last Element and Remainder

Assigning the first element and the remainder of an array to a variable is common, but you can also do the same in reverse
TIL: Denaturing Ruby Array to get the Last Element and Remainder
Photo by Anne Nygård / Unsplash

Assigning the first element and the remainder of an array to a variable is common, but you can also do the same in reverse.

Getting the first element and remainder:

array = [1,2,3,4]
first, *remainder = array
# first = 1
# remainder = [2,3,4]

You can also do the same from the tail:

array = [1,2,3,4]
*prefix, last = array
# prefix = [1,2,3]
# last = 4

Oh, and you can also get the first and last and ignore the remainder:

array = [1,2,3,4]
first, *, last = array
# first = 1
# last = 4