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