Get last nth elements from Enumerable in #Elixir

June 23, 2018|
1 min read
  • 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]

© 2023, Dorian Karter