liveBook · Manning

First element

As explained in The Well-Grounded Rubyist, Fourth Edition

first is an Enumerable method that returns the first element or a specified number of initial elements from an enumerable object.

first retrieves the first item produced by an enumerable. With an array or range, calling first without an argument returns one object; passing n returns an array containing the first n objects, even when n is 1. section 9.2.5 section 10.4.1

The returned value follows the enumerable's iteration behavior:

  • An array returns its initial element, while a range returns the first value it yields. section 10.4.1
  • A hash returns its first inserted key/value pair as a two-element array. section 10.4.1
  • The method finds the beginning of an iteration, unlike last, which has no general meaning for an enumerable that can continue forever. section 10.4.1

Taking a finite prefix from an infinite sequence

A finite range can be filtered and then queried directly, but an infinite range must be lazy: `(1..Float::INFINITY).lazy.select { |n| n % 3 == 0 }.first(10)` returns `[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]`. The lazy pipeline evaluates only enough values to produce the requested ten results. Alternatively, `take(n).force` converts a selected lazy prefix into an ordinary result array. section 10.12

Table 9.2 Summary of common array query methods

Method name/sample call

Meaning

a.size (synonyms: length, count)

Number of elements in the array

a.empty?

True if a is an empty array; false if it has any elements

a.include?(item)

True if the array includes item; false, otherwise

a.count(item)

Number of occurrences of item in array

a.first(n=1)

First n elements of array

a.last(n=1)

Last n elements of array

a.sample(n=1)

n random elements from array

Compare first with size, empty?, include?, count, last, and sample to see how array queries differ in purpose and return shape. section 9.2.5

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains return shapes, hash iteration, infinite enumerables, and lazy evaluation, but does not exhaustively catalog Enumerable methods.
Examples
Uses arrays, ranges, hashes, an infinite die iterator, and multiples of three selected from an infinite range.
What you can do after
Apply it via Ruby's Enumerable API to obtain one item or a finite initial slice from an iterable, including lazy infinite sequences.
How it connects
Connects first to Enumerable, each, hashes, lazy enumerators, select, take, force, and the contrasting behavior of last.

Also explained in

Compare how 2 books explain first element →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.