liveBook · Manning

Take

As explained in The Well-Grounded Rubyist, Fourth Edition

take is an Enumerable method that returns a specified number of elements from the beginning of an enumerable.

take returns a specified number of elements from the beginning of an Enumerable. Unlike first, which returns one element by default, take returns the selected group; unlike drop, it keeps the elements before the dividing point. section 10.4.2 section 10.4.1

Taking from an array

states = %w(NJ NY CT MA VT FL) states.take(2) # => ["NJ", "NY"] states.drop(2) # => ["CT", "MA", "VT", "FL"] Both methods divide the collection after two elements, but take returns the beginning and drop returns what remains. section 10.4.2

Use related forms when the stopping rule is not a fixed number:

  • take_while collects elements from the beginning while its block remains truthy, then stops at the first failure. section 10.4.2
  • take is anchored to iteration order, so it stops after satisfying the quantity rather than searching through the whole collection. section 10.4.2
>> my_enum = (1..Float::INFINITY).lazy.select {|n| n % 3 == 0 }
=> #<Enumerator::Lazy: #<Enumerator::Lazy: 1..Infinity>:select>
>> my_enum.take(5).force
=> [3, 6, 9, 12, 15]
>> my_enum.take(10).force
=> [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]

A lazy enumerator can use take to bound work over an infinite sequence; call force to obtain the resulting array. section 10.12

Taking from an infinite sequence

my_enum = (1..Float::INFINITY).lazy.select { |n| n % 3 == 0 } my_enum.take(5).force # => [3, 6, 9, 12, 15] Without lazy enumeration, operations such as map or select cannot finish on an endless enumerable. take supplies the finite boundary. section 10.12

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains fixed-count and predicate-based stopping, then extends the behavior to lazy and infinite enumeration.
Examples
Demonstrates arrays, state-code prefixes, multiples of three, infinite ranges, and bounded FizzBuzz output.
What it assumes
Assumes familiarity with collections and blocks while establishing Enumerable iteration, first, drop, and lazy enumerators.
What you can do after
Apply it via Ruby's Enumerable API to obtain finite prefixes from ordinary or lazy collections.
How it connects
Connects take with Enumerable, Enumerator, first, drop, take_while, drop_while, select, map, and lazy enumeration.

Also explained in

Compare how 4 books explain take →

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.