How to Use the Ruby last Method

09/24/2021

Contents

In this article, you will learn how to use the Ruby last method.

Using the Ruby last method

The last method in Ruby is used to retrieve the last element or a specified number of elements from an array or a range. It returns the last element or elements of the object it is called on.

Syntax

The basic syntax of the last method is as follows:

object.last(n)

Parameters

  • object: An array or a range object.
  • n: An optional parameter that specifies the number of elements to be returned. If n is not provided, the method returns the last element of the object.

Examples

If the object is an array, the last method returns the last n elements of the array in the form of an array. If n is greater than the size of the array, the method returns the whole array. If n is negative, the method raises an ArgumentError.

Example:

arr = [1, 2, 3, 4, 5]
arr.last      #=> 5
arr.last(2)   #=> [4, 5]
arr.last(10)  #=> [1, 2, 3, 4, 5]
arr.last(-1)  #=> ArgumentError: negative array size

If the object is a range, the last method returns the last element of the range if n is not provided. If n is provided, it returns an array of the last n elements of the range.

Example:

range = (1..5)
range.last      #=> 5
range.last(2)   #=> [4, 5]

Note that the last method does not modify the original array or range.

In addition to the last method, there are also first and take methods in Ruby that are similar to last. The first method returns the first element or elements of an array or range, while the take method returns the first n elements of an array or range.

Example:

arr = [1, 2, 3, 4, 5]
arr.first      #=> 1
arr.first(2)   #=> [1, 2]
arr.take(3)    #=> [1, 2, 3]

range = (1..5)
range.first    #=> 1
range.first(2) #=> [1, 2]
range.take(3)  #=> [1, 2, 3]