The cycle method in Ruby

Ridin' cyclin' chillin'

July 10th, 2015

After 4 weeks of phase 0 at Dev Bootcamp, I can officially declare that I’m awesome at Ruby. Ok, I’m getting a little carried away here. The mountain is high, and the more I learn the taller it gets. To avoid a panic attack I’ll take a step back and try to explain as well as possible one method. Baby steps they say. So today is about the cycle method, part of the module of enumerables.

Ridin’ chillin'

This is how we could recap enumerables, it’s a family of methods that will apply an action to data contained in hashes and arrays. They are tremendously useful when processing datasets: updating artists information in your favorite playlist (iTunes is for losers, I prefer Sublime) or going through a series of fields in a form.

Cyclin'

In the spirit of enumerable the cycle method will literally cycle through an array (or hash) and do what you will instruct it to do in the code block. If you don’t specify anything it will do it forever, but you can also state a number of cycles. See below.

a = ["Jackson 5", "Drake", "Mika"]
        a.cycle { |x| puts x }  # print, Jackson 5, Drake, Mika, Jackson 5, Drake, Mika,.. forever.
        a.cycle(2) { |x| puts x }  # print, Jackson 5, Drake, Mika, Jackson 5, Drake, Mika.

Example of application

You are in charge of the sign up process of the latest trendy app. You want to make sure that all the fields are filled out, the cycle method is perfect to help you display a message in case one of the field is left unfilled, assuming you are using a hash with x as the name of the fields and y as the value of the field:

hash.cycle(1) {|x,y| if y.empty? return "Hey, some information is missing! You don't get to be trendy until you've properly filled out this form!"}

And boom, you’re on your way to making millions!