Get last nth elements from Enumerable in #Elixir

June 23, 2018

  • elixir

Originally posted by me on Hashrocket TIL

You probably know about Enum.take(n) where n is a number dictating how many elements you want to take from an Enumerable. Use it like this:

[1, 2, 3, 4, 5]
|> Enum.take(3)
# => [1, 2, 3]

But how can you get the last 3 elements? Just use a negative number!

[1, 2, 3, 4, 5]
|> Enum.take(-3)
# => [3, 4, 5]

Written by Dorian Karter, a Sr. Software Engineer
Github | Twitter

© 2021, Dorian Karter