Array#first

arr.first(n=nil) -> obj or array
Returns: object or array · Updated March 13, 2026 · Array Methods
arrays elements access

Array#first retrieves the first element from an array. It provides a clean, readable way to access elements without using index notation.

Syntax

arr.first      # returns first element
arr.first(n)   # returns first n elements as array

Parameters

ParameterTypeDefaultDescription
nIntegernilWhen provided, returns an array of the first n elements instead of a single element

Examples

Basic usage

fruits = ["apple", "banana", "cherry", "date"]

# Get the first element
fruits.first
# => "apple"

# Get first n elements
fruits.first(2)
# => ["apple", "banana"]

With empty arrays

empty = []

# Single element returns nil on empty array
empty.first
# => nil

# With n parameter returns empty array
empty.first(3)
# => []

With various data types

# Works with any object types
mixed = [42, "hello", :symbol, [1, 2], { key: "value" }]

mixed.first
# => 42

mixed.first(3)
# => [42, "hello", :symbol]

Common Patterns

Check if array has elements

# Common pattern: check presence before accessing
if array.any?
  first_item = array.first
end

Get extremes of sorted data

# Often used with sorted data
scores = [95, 87, 92, 88, 79, 91]

# Or using first after sorting
sorted = scores.sort
lowest = sorted.first

Preview large datasets

# Preview first items without loading entire dataset
logs = ["2024-01-01", "2024-01-02", "2024-01-03", "2024-01-04", "2024-01-05"]

puts "First 3 entries:"
logs.first(3).each { |log| puts "  #{log}" }

Queue operations

# First element often serves as queue front
queue = ["task1", "task2", "task3"]
next_task = queue.first
# => "task1"

Error Cases

This method never raises exceptions:

# Single element access returns nil
[].first   # => nil

# With n parameter returns empty array
[].first(5)  # => []

# n greater than array length returns all elements
[1, 2].first(10)
# => [1, 2]

See Also