first method

The first method takes an enumerable collection and optional number of elements. If no element count is given, it returns the first element in the collection. If a number is given, it returns that many elements from the beginning of the collection. Careful! This can be tricky, since it returns different types of objects (scalars or arrays) depending on the paramenters given.

Number List

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

# first number:
@numbers.first
    #=> 1

# first three numbers:
@numbers.first(3)
    #=> [1, 0, 3]

Pet Inventory

# first pet on the list:
@inventory.first.name
    #=> "dog"

# first 3 pets on the list:
@inventory.first(3).map(&:name)
    #=> ["dog", "cat", "fish"]

Pokey Things

# first pokey thing:
@pokey_things.seek(0)
@pokey_things.first.chomp
    #=> "cactus"

# first three pokey things:
@pokey_things.seek(0)
@pokey_things.first(3).map(&:chomp)
    #=> ["cactus", "pole", "knife"]

Heroku Log File

# first heroku request:
@requests.first.id
    #=> 1

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

Leave a Reply

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