partition method

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.

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"]

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>