Technical Blog : Enumerable#Cycle

7/12/2015

This week I'll be explaining a little bit about an enumerable, specifically, the Enumerable#Cycle method. According to the Ruby Documentation, "An Enumerable provides a collection of classes with several traversal and searching methods, in addition an Enumerable can sort." What does this mean? If you have a container of information, an array can be an example of a container of information. If you are unsure of what an array is, please refer to previous blog posts. To continue, if we have an array of information and need to move THROUGH the array according to some logic, we would want to use an enumerable.

Why would we use the Enumerable#Cycle method? The Cycle method allows you to run through the container of information FOREVER, or a certain amount of times if you give the Enumerable a positive integer input of how many times you want to run through your code after you declare the Cycle method.
For Example:
If you have an array

array = [1,2,3,4]

and you want to run through the numbers n times. We can use the Enumerable#Cycle method

array.cycle(2) {|number| puts number}

Here we are telling the Cycle method to run through the array 2 times, then in our code block (everything between the {} is our code block) to put number which is the number the enumerable is on, to the print the number to the console. Get it? Got it? Good.

This would be what the terminal would output for us:

1 2 3 4 1 2 3 4

Now that we have a foundation with the Enumerable, things are about to get a little more complicated. With respect to the Cycle method, an Enumerable will run FOREVER until nil is given to the code block. Also, if the container of information is empty or the number given to the Enumerable is a non-positive integer, the Enumerable does NOTHING.

The code for this case would look something like this:

array.cycle(-1) {|number| puts number} -> Would return "nil"

But if we want the program to run FOREVER we would run something like this:

array.cycle {|number| puts number}

I hope by reading this blog post you will now be equipped to use an Enumerable in your next ruby adventure.

Thanks for reading!

-Scott