take method

The take method works very similarly to first; it takes an enumerable collection and returns the first n elements from the list. Unlike first, however, it always returns an array, and the parameter is not optional.

Number List

@numbers = [1, 0, 3, 2, 5, 4, 7, 6, 9, 8]

# taking only the first two numbers:
@numbers.take(2)
    #=> [1, 0]

# taking numbers:
@numbers.take(0)
    #=> []

Pet Inventory

# taking the first two pets:
@inventory.take(2).map(&:name)
    #=> ["dog", "cat"]

# taking no pets:
@inventory.take(0).map(&:name)
    #=> []

Pokey Things

# taking first pokey thing:
@pokey_things.seek(0)
@pokey_things.take(1).map(&:chomp)
    #=> ["cactus"]

# taking no pokey things:
@pokey_things.seek(0)
@pokey_things.take(0).map(&:chomp)
    #=> []

Heroku Log File

# taking first 3 heroku requests:
@requests.take(3).map(&:id)
    #=> [1, 2, 3]

# taking no heroku requests:
@requests.take(0).map(&:id)
    #=> []

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>