each_slice method

The each_slice method takes an enumerable collection and a number parameter, and yields that number of elements at a time to the given block.

Pet Inventory

# pets grouped by two:
inventory.each_slice(2){|pets| p pets.map(&:name)}

# output
# ["dog", "cat"]
# ["fish", "scorpion"]
# ["beetle", "monkey"]
# ["rock"]

# pets grouped by three:
inventory.each_slice(3){|pets| p pets.map(&:name)}

# output
# ["dog", "cat", "fish"]
# ["scorpion", "beetle", "monkey"]
# ["rock"]

Leave a Reply

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