Ruby/Rails – Get the first n elements or last n elements in an array

Let say we have 100 element in our array and we need to get first n elements we can use this command.

numbers = [ 1, 2, 3, 4, 5, 6, 7, 8 ]
numbers.pop(2) # => [1, 2, 3, 4, 5, 6]

numbers # => [7,8]

And to get n last elements we can use last() function with parameter inside

numbers = [ 1, 2, 3, 4, 5, 6, 7, 8 ]
numbers.last(2) # => [7,8]

numbers # => [ 1, 2, 3, 4, 5, 6, 7, 8 ]

You also can consider if we use pop() function it will change the numbers array elements. on the other hand, last() function does not change the numbers array elements

Leave a Comment