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.
- View the objects used in these examples
- View these examples as a runnable ruby script on GitHub.
- Practice this method as an interactive kata on Codewars!
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]