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



