The partition method calls the given block for each element in the collection, and separates them into items that returned true, and those that didn't. It returns the two arrays.
- 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
pet_lists = inventory.partition{|pet| pet.legs == 4} # pets with exactly four legs: pet_lists[0].map(&:name) #=> ["dog", "cat"] # pets without exactly four legs: pet_lists[1].map(&:name) #=> ["fish", "scorpion", "beetle", "monkey", "rock"] pet_lists = inventory.partition(&:low_inventory?) # pets with low inventory: pet_lists[0].map(&:name) #=> ["cat", "scorpion", "monkey", "rock"] # pets with plenty of inventory: pet_lists[1].map(&:name) #=> ["dog", "fish", "beetle"]