collect/map methods

The collect/map methods take an enumerable collection, runs each item through the given block, and returns a new array of the results.

Number List

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

# all numbers multiplied by two:
@numbers.map{|number| number * 2}
  #=> [2, 0, 6, 4, 10, 8, 14, 12, 18, 16]

# the even status for all numbers:
@numbers.map(&:even?)
    #=> [false, true, false, true, false, true, false, true, false, true]

Pet Inventory

# leg counts for all pets:
@inventory.map(&:legs)
    #=> [4, 4, 0, 8, 6, 2, 0]

# leg totals for each pet type:
@inventory.map{|pet| pet.legs * pet.quantity}
    #=> [400, 200, 0, 8, 60000, 4, 0]

Pokey Things

# letter counts for all pokey things:
@pokey_things.seek(0)
@pokey_things.map{|thing| thing.chomp.size}
    #=> [6, 4, 5, 41]

# all pokey things, capitalized:
@pokey_things.seek(0)
@pokey_things.map(&:chomp).map(&:capitalize)
    #=> ["Cactus", "Pole", "Knife", "Cactus holding poles with knives attached"]

Heroku Log File

# request methods for all heroku requests:
@requests.map(&:method)
    #=> ["GET", "GET", "GET", "GET", "GET", "GET", "GET", "GET", "GET", "GET", "GET", "GET", "GET", "GET", "GET", "GET", "GET", "GET", "GET", "GET", "GET", "POST", "GET", "GET", "GET", "GET", "GET", "GET", "GET", "GET", "GET"]

# total response times for all heroku requests:
@requests.map{|request| request.connect + request.service}
    #=> [1459, 1642, 17, 2, 1, 1, 3, 0, 1008, 1, 2, 1015, 994, 1371, 18, 10, 2, 17, 2, 2, 1, 60, 3, 912, 1, 5, 697, 3, 863, 1318, 696]

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>