Enumerating Enumerable: Enumerable#each_cons

Welcome to the ninth installment of Enumerating Enumerable, the series of articles where I attempt to do a better job at documenting Ruby’s Enumerable module than Ruby-Doc.org does.

I’m going through the Enumerable‘s methods in alphabetical order, and we’ve reached the methods that are variations on each In this article, I’m going to cover each_cons, which got introduced in Ruby 1.9.

If you missed any of the earlier articles, I’ve listed them all below:

Enumerable#each_cons and Arrays

When used on an array and given a block and a number n as an argument, each_cons is like an each that goes through each element in the array and outputs an n-sized array slice of the original array starting at the current element.

each_cons is one of those methods that’s really tough to describe. This is one of those cases where a demonstrating trumps describing…

each_cons can also be used without providing a block. In this case, you’re using it to create an Enumerator object that you can then use to spit out array slices when you call its next method:

Swift

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

#Let's create an enumerator that we can use to give us three-person

# superhero teams

teams_of_3 = justice_league.each_cons(3)

=> #<enumerable::Enumerator:0x007f8f83ecc538>

# Let'sgetthe first team of3

teams_of_3.next

=>["Aquaman","Batman","Black Canary"]

#Now the next one...

teams_of_3.next

=>["Batman","Black Canary","Flash"]

teams_of_3.next

=>["Black Canary","Flash","Green Arrow"]

teams_of_3.next

=>["Flash","Green Arrow","Green Lantern"]

#Let'sgo back tothe first team of3

teams_of_3.rewind

=>#<enumerable::Enumerator:0x007f8f83ecc538>

teams_of_3.next

=>["Aquaman","Batman","Black Canary"]

Enumerable#each_cons and Hashes

When used on a hash and given a block and a number n as an argument, each_cons is like an each that goes through each element in the array and outputs an n-sized array slice of the hash starting at the current element. Note that in the process, hash elements are converted into two-element arrays where the first element contains the key and the second element contains the corresponding value.