Array#last
arr.last(n=nil) -> obj or array 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
The no-argument form returns a single element, which can be any object including nil when the array is empty. The integer form always returns an array, even when the argument is 1, which means callers can rely on array methods like each and map without checking the return type first.
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"]
Calling last without an argument gives you the final element as a single value, while passing an integer returns a slice of the last n elements as a new array. The distinction matters because the return type changes: a single object in the first case, an array in the second.
With empty arrays
empty = []
# Single element returns nil on empty array
empty.last
# => nil
# With n parameter returns empty array
empty.last(3)
# => []
Empty arrays are handled gracefully: last without arguments returns nil, and last(n) returns an empty array. This means you can safely call last on a collection that might be empty without wrapping it in a guard clause, which keeps the calling code simpler.
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"}]
last works with arrays of any content type because it only cares about position, not about the values themselves. Whether the elements are numbers, strings, symbols, nested arrays, or hashes, the method simply returns whatever sits at the end of the collection or in the trailing slice.
Common Patterns
Check if array has elements
# Common pattern: check presence before accessing
if array.any?
last_item = array.last
end
Pairing any? with last is a defensive pattern that avoids calling last on an empty collection when the result would be misleading. The guard clause keeps the intent clear: only access the last element when there is actually something to access.
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
Sorting before calling last is a common way to find the maximum value in a collection. While max is the more direct method for that purpose, the sort-then-last pattern is still worth knowing because it makes the entire sorted array available for other uses, not just the extreme value.
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}" }
Using last(n) to preview the most recent entries in a log or time series is a clean pattern for dashboards and monitoring code. The method reads naturally because “last” already carries the meaning of “most recent” when the data is ordered chronologically, and the integer argument gives you control over how many entries to show.
Stack operations
# Last element often serves as stack top
stack = ["a", "b", "c"]
top = stack.last
# => "c"
Treating the last element as the top of a stack is a lightweight pattern that avoids the need for a dedicated stack class. Pushing with << and peeking with last gives you the essential stack operations without any extra abstraction, which is often enough for simple depth-first traversals and undo stacks.
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]
Use last when the tail matters
last is the natural choice when the end of the array carries the interesting value. That might be the most recent log entry, the top item on a stack, or the newest record in a sorted list. The method keeps the intent obvious because the call says exactly what part of the array you care about. That is often better than indexing from the end by hand, especially when the code is meant to be read quickly by someone who needs to understand the shape of the data.
Empty arrays stay predictable
The method has a clear answer for empty arrays, which makes it easier to use in normal control flow. A single-item lookup returns nil, and asking for a slice returns an empty array. That means the caller can usually keep moving without special error handling. When the code already knows how to deal with nil or an empty list, last gives you a calm and predictable result instead of a branch-heavy detour.
Match it to an ordered sequence
last is especially readable when the array is already ordered by time, priority, or some other meaningful rule. It can show the newest item, the final item in a queue, or the end of a sorted batch that you want to inspect next. Used with sort, take, or reverse, it becomes part of a small sequence of steps that stays easy to follow. That makes the method useful both in everyday code and in more deliberate processing pipelines.