Let's cycle until we break!

How to use Enumerable's Cycle method!

24/11/2014

Have you ever asked yourself: How can I create an infinitely-repeating ordered source of colletion items? No? Well, neither have I! But it's good to know I can!

So how do we do that? Quite simple. We just have to use the method cycle. You call it on an array and pass a block, then it will pass each array item to the block, when it finishes it will just start again from the beginning. Here goes an example:

months_of_the_year.cycle {|month| puts month} => January February March April May June July August September October November December January February ...

Just cycling through things indefinitely doesn't sound too useful, does it? What useful things can I do with it? That's a good question! You can store the cycling array inside a variable and use .next inside it to find what comes next.

months = months_of_the_year.cycle months.next => February

If you want to start over you can use .rewind instead of .next and it will go back to the beginning.

Let's try a more practical example:

months = %w{January February March April May June July August September October November December}.cycle topics = %w{Git Github HTML CSS Ruby RoR JavaScript Sinatra Logic Yoga EmotionalIntelligence Empathy Node Angular}.cycle 14.times do month = months.next topic = topics.next puts "On #{month} we will learn #{topic}" end

The code above will assign each topic to a month and since we have more topics than we have months it will keep assigning topics from january after it passes december.

I hope this was easy to follow and you learned something from it!