collect_concat method

The collect_concat method works much like map. It takes an enumerable collection, runs the given block once for each item, and returns a new array of the results. Before returning the results, however, if flattens the array. So if your block itself returns an array, these sub-arrays will be flattened into one larger array before being returned.

Pet Inventory

# names and legs:
inventory.collect_concat{|pet| [pet.name, pet.legs]}
    #=> ["dog", 4, "cat", 4, "fish", 0, "scorpion", 8, "beetle", 6, "monkey", 2, "rock", 0]
# names and in stock status:
inventory.collect_concat{|pet| [pet.name, pet.in_stock?]}
    #=> ["dog", true, "cat", true, "fish", true, "scorpion", true, "beetle", true, "monkey", true, "rock", false]

Leave a Reply

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