rubyguides

Enumerable#first

What does first do?

first returns the first element of a collection, or the first n elements if an argument is provided. It is defined on Enumerable and works with arrays, ranges, hashes, and any other object that mixes in the Enumerable module.

When called without an argument on an empty collection, first returns nil. When called with an argument on an empty collection, it returns an empty array.

Basic Usage

Get the first element

[10, 20, 30, 40].first
# => 10

The most common use of first is on arrays, where it pulls the element at index zero. Because the method comes from the mixin rather than Array, it works on any object that responds to each — ranges, sets, lazy enumerators, and custom iterables all behave the same way. Code written with first stays readable regardless of the collection type.

Works with ranges:

(1..10).first
# => 1

A Ruby Range iterates lazily, so first pulls the start value without building the full sequence. Calling it on (1..Float::INFINITY) is safe because the method grabs only the beginning point. Reaching for first on a range often reads more naturally than converting to an array first.

Get the first n elements

[10, 20, 30, 40, 50].first(3)
# => [10, 20, 30]

Passing an integer to first changes the return type: you always get back an Array. Asking for more elements than the collection holds does not raise an error — first(100) on a three-element array returns all three. This forgiving design fits Ruby’s philosophy of giving you what it can without defensive length checks.

When called with an argument, first always returns an array — even if you ask for just one element:

[10, 20, 30].first(1)
# => [10]

The distinction between first and first(1) trips up newcomers. Calling first with no argument gives you a raw element — a number, a string, or nil. Calling first(1) wraps that element in an array. This matters when downstream code expects uniform types: passing the result to map or each behaves differently depending on which form you chose.

This is different from calling first without arguments, which returns a single element or nil.

Empty Collections

first handles empty collections gracefully:

[].first
# => nil

[].first(3)
# => []

Many Ruby methods raise exceptions on empty data — division by zero throws ZeroDivisionError. With first, the designers chose the path of least surprise: return a safe fallback and let the caller decide. An empty array with first(n) produces an empty array, composing cleanly with each, map, and select without guard clauses. You can chain operations without checking whether earlier steps emptied the data.

This behaviour makes first safe to call without checking whether the collection is empty first.

first(n) vs take(n)

first(n) and take(n) are similar but have important differences:

Aspectfirst(n)take(n)
Defined onArray onlyEnumerable
Return typeArrayArray
On empty collection[][]
Works with lazy enumerablesNoYes
# first is an Array method — converts enumerables to arrays first
(1..5).first(2)
# => [1, 2]

# take is Enumerable — works directly with lazy enumerables
(1..5).lazy.take(2).to_a
# => [1, 2]

The key practical difference: take is defined on Enumerable and works with lazy enumerators, while first is an Array method that eagerly evaluates its receiver.

The choice between these two comes down to memory. With a moderate-sized collection, first(n) materializes the array in a single pass and works fine. When the pipeline reads from a large file or external stream, lazy.take(n) defers allocation until the last moment. You rarely notice in scripts, but inside a web worker processing uploads it becomes measurable.

The head Idiom

In functional programming traditions — and in some Ruby codebases — you may see head used to mean “first element”. Ruby doesn’t define a head method by default, but it is a common convention when working with lists or recursive data structures:

# A common pattern for extracting head and tail
head, *tail = [10, 20, 30, 40]
head  # => 10
tail  # => [20, 30, 40]

The head, *tail destructuring comes from languages with pattern-matching like Haskell and Elixir. Ruby lacks tail-call optimization, but the pattern communicates intent when splitting a list into its leading element and the rest. For most Ruby code, using first with array slicing expresses the same operation in a way that matches standard library conventions.

# This is functionally equivalent to:
[10, 20, 30, 40].first   # => 10

Ruby’s built-in first is more explicit and idiomatic than the head convention. The method name reads like English prose, as Matz intended. Calling arr.first leaves no doubt about intent, while head, *tail = arr requires understanding destructuring. Prefer first unless the algorithm benefits from head/tail framing, such as recursive tree-walking functions.

Using with Enumerators

first works with enumerators created by other Enumerable methods:

# Create an enumerator by chaining methods
enum = [1, 2, 3, 4, 5].map.with_index

enum.first
# => [1, 0]

Enumerator objects act as composable iteration pipelines. When you call map.with_index, nothing runs — the enumerator remembers the steps. Only when you demand a value with first, to_a, or each does Ruby start walking the chain. This lazy design lets you stack transformations without intermediate arrays growing in memory, enabling patterns like staged processing and external iteration.

Enumerators are lazy by default, so combining first with enumerator methods can be efficient:

result = (1..1000).each_slice(10).first
# => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

When you chain each_slice(10) on a range and call first, Ruby carves out only the first group and stops. The enumerator yields batches on demand, so work is proportional to what you ask for, not the source size. This pattern shows up in pagination and batch processing, where you want the first page without computing every page.

Practical Examples

Getting the first match

Use first after filtering with select or find to get the first matching result:

numbers = [3, 1, 4, 1, 5, 9, 2, 6]

# Get first even number
numbers.select(&:odd?).first
# => 3

# Get first element greater than 5
numbers.find { |n| n > 5 }
# => 9

Chaining select with first is a common Ruby idiom, but select builds the full filtered array before first picks one element. For large collections, prefer find (or detect) — it stops iterating the moment a block returns true. Knowing “filter then take one” versus “stop at first match” avoids performance problems in hot paths.

Getting the first n items

Often used with sort, group_by, or other Enumerable methods:

users = [
  { name: "Alice", score: 95 },
  { name: "Bob", score: 87 },
  { name: "Carol", score: 92 },
  { name: "Dave", score: 78 }
]

# Get top 3 performers
users.sort_by { |u| -u[:score] }.first(3)
# => [{ name: "Alice", score: 95 },
#      { name: "Carol", score: 92 },
#      { name: "Bob", score: 87 }]

Sorting a collection and calling first(n) is the standard Ruby pattern for top-N queries. Negating the key in sort_by gives descending order since Ruby lacks sort_by_desc. After sorting, first(3) grabs the leading entries from the already-materialized array at no extra cost. For typical application code, the sort-then-take approach is both readable and fast.

first with find

Combine first with find for early termination in searches:

# Find the first user with a specific role, then get their name
users = [
  { name: "Alice", role: "admin" },
  { name: "Bob", role: "viewer" },
  { name: "Carol", role: "admin" }
]

users.find { |u| u[:role] == "admin" }[:name]
# => "Alice"

The find method (aliased as detect) locates the first matching element. Unlike select.first, which scans everything and builds an intermediate array, find exits early when a match occurs. The block accepts any Ruby expression, so you can test nested hash keys, call instance methods, or combine conditions with logical operators.

first with lazy

Use lazy to defer evaluation when working with large or infinite sequences:

# Get first 5 squares of even numbers
(1..).lazy \
  .map { |n| n ** 2 } \
  .select(&:even?) \
  .first(5)
# => [4, 16, 36, 64, 100]

The endless range (1..) combined with lazy produces values only as needed. Without lazy, calling map on an endless range runs forever. With lazy, each step becomes a pull-based generator: first(5) requests five values, the pipeline computes five squares and filters for evenness, then stops. Use this pattern when reading the first matching lines from a large log file or sampling paged API results.

This is more efficient than evaluating the entire sequence before extracting results.

With hashes

first on a hash returns the first key-value pair as a two-element array:

{ a: 1, b: 2, c: 3 }.first
# => [:a, 1]

{ a: 1, b: 2, c: 3 }.first(2)
# => [[:a, 1], [:b, 2]]

Since Ruby 1.9, hashes maintain insertion order, so first returns the pair added earliest. This ordering guarantee makes the method reliable for FIFO processing or showing the most recently added entry. When passed an argument, first(n) returns an array of key-value arrays. Destructure the result with key, value = hash.first when you need keys or values individually.

Performance Notes

first is O(1) when called without arguments — it simply returns the first element without iteration.

When called with an argument first(n), it must collect n elements, making it O(n) in the size of n (not the collection). For very large n, consider whether you actually need all n elements upfront.

For lazy evaluation with large or infinite collections, prefer take with lazy:

# Eager — builds the entire array first
(1..1_000_000).first(10)

# Lazy — only evaluates what is needed
(1..1_000_000).lazy.first(10)

See Also