Passing argument with Array#first and Array#last Methods

Did you know that you can pass an argument to the Array#first and Array#last methods to return a specific number of elements from the beginning or end of the array?

The Array#first method returns the first element of the array, or the first n elements if an argument is provided. For example:

 array = [1, 2, 3, 4, 5]

 array.first           # => 1
 array.first(3)        # => [1, 2, 3]

Likewise, the Array#last method returns the last element of the array, or the last n elements if an argument is provided. For example:

 array = [1, 2, 3, 4, 5]

 array.last            # => 5
 array.last(3)         # => [3, 4, 5]

So next time you need to access the first or last n elements of an array in Ruby, remember the Array#first and Array#last methods with an argument!

Read more 🔖