meghan kline tuls

Post #4: Enumerable#cycle

How does it work?

June 13, 2015

Cycle is another aptly named method in Ruby. When #cycle is called on an array, the method cycles through each element infinitely unless a break is called or an argument is used.

For example,

        array = ["mama", "papa", "baby"]
        array.cycle 
        #=> mama, papa, baby, mama, papa, baby, mama, papa, baby, mama, papa, baby, mama, papa, baby, mama...
        

Whereas,

array.cycle(2) #=> mama, papa, baby, mama, papa, baby

If you wish to print the cycle to the console, then you can use the block:

        array.cycle(3) {|x| puts x}
      

The cycle could also be stopped at a specific point such as,

        array.cycle do |x|
        break if x == "papa"
      

The #cycle method does not automatically store the values, so you could choose to make a new array and push the cycled values to the array.

Hopefully you are starting to think of some situations where #cycle might be useful. This might incude when are you looking to assign roles or positions to a group of people. You could combine the #zip and the #cycle methods to create a distribution of responsiblities. Unfortunately #cycle will only run a complete course. It is not possible to stop at a certain number of elements except at the end of a full cycle. I think this is probably the biggest limitation of the method, similar to n.times do.