Reflections

Ruby Enumerable#cycle method

DBC Phase 0 Week #4

November 21, 2014

The Enumerable#cycle method goes through list a (array, hash..etc) n number of times and calls a block of things to do on each element or it returns a enumerator if there is no block. I'll explain what this means this enumerator is later on.

        months = ["January", "February", "March"]

        months.cycle(2) {|x| puts x }

        #=>
        January
        February
        March
        January
        February
        March 

Here months is an array of 3 strings. It cycles through the array 2 times and when going over each element it prints the element. If I took out the "(2)" and left it blank it would do an infinite loop and continue to cycle through the array.

        which_month = months.cycle

        => #

        which_month.next
        => "January"

        which_month.next
        => "February"

        which_month.next
        => "March"

        which_month.next      #it cycles back to the beginning of the list
        => "January"

        which_month.next
        => "February"

        which_month.rewind        #makes it start back at the top of the list
        => #

        which_month.next
        => "January"
            

Here I didn't add any arguments to the cycle method. I made a new variable "which_month" and pointed to cycle the months list. This turned the array into a enumerator. I am now able to use the ".next" method on the variable and it'll return the next item in the list, starting from the top. ".rewind" makes it go back to the beginning of the array. Why would making it into an enumerator useful? Here's an example:

                days = [31, 28, 31]      #Let's pretend it's not a leap year
                days_cycle = days.cycle
                which_month.rewind              #We want to make sure we start at the
                                                beginning of the array
                3.times do
                    month = which_month.next
                    days_of_month = days_cycle.next
                    puts "#{month} has #{days_of_month} in the month."
                end

                #=> 
                January has 31 in the month.
                February has 28 in the month.
                March has 31 in the month.
           

Using the Enumerator#cycle method on both arrays, I was able to use both lists to make a combined output. Now go try to use these methods.