Array#last
arr.last(n=nil) -> obj or array Returns:
object or array · Updated March 13, 2026 · Array Methods arrays elements access
Array#last retrieves the last element from an array. It provides a clean, readable way to access elements without using index notation.
Syntax
arr.last # returns last element
arr.last(n) # returns last n elements as array
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
n | Integer | nil | When provided, returns an array of the last n elements instead of a single element |
Examples
Basic usage
fruits = ["apple", "banana", "cherry", "date"]
# Get the last element
fruits.last
# => "date"
# Get last n elements
fruits.last(2)
# => ["cherry", "date"]
With empty arrays
empty = []
# Single element returns nil on empty array
empty.last
# => nil
# With n parameter returns empty array
empty.last(3)
# => []
With various data types
# Works with any object types
mixed = [42, "hello", :symbol, [1, 2], { key: "value" }]
mixed.last
# => {:key=>"value"}
mixed.last(3)
# => ["hello", :symbol, {:key=>"value"}]
Common Patterns
Check if array has elements
# Common pattern: check presence before accessing
if array.any?
last_item = array.last
end
Get extremes of sorted data
# Often used with sorted data
scores = [95, 87, 92, 88, 79, 91]
# Or using last after sorting
sorted = scores.sort
highest = sorted.last
Preview large datasets
# Preview last items without loading entire dataset
logs = ["2024-01-01", "2024-01-02", "2024-01-03", "2024-01-04", "2024-01-05"]
puts "Last 3 entries:"
logs.last(3).each { |log| puts " #{log}" }
Stack operations
# Last element often serves as stack top
stack = ["a", "b", "c"]
top = stack.last
# => "c"
Error Cases
This method never raises exceptions. The behavior with empty arrays is well-defined:
# Single element access returns nil
[].last # => nil
# With n parameter returns empty array
[].last(5) # => []
# n greater than array length returns all elements
[1, 2].last(10)
# => [1, 2]