each_cons method

The each_cons method takes an enumerable collection and iterates through a cascading list of elements. For instance, a list of [1, 2, 3, 4] called with each_cons(2) would yield [1,2], [2,3], and finally [3,4].

Pet Inventory

# Pet inventory by name: ['dog', 'cat', 'fish', 'scorpion', 'beetle', 'monkey', 'rock']

# pets in cascading groups of two:
inventory.each_cons(2){|pets| p pets.map(&:name) }

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

# pets in cascading groups of three:
inventory.each_cons(3){|pets| p pets.map(&:name) }

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

Leave a Reply

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