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 |
|---|---|
|
|
Number of elements in the array |
|
|
True if |
|
|
True if the array includes |
|
|
Number of occurrences of |
|
|
First n elements of array |
|
|
Last n elements of array |
|
|
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

