Enumerable#cycle




   Big Wheel



.cycle

I researched enumerable#cycle primarily because I like bicycles.

Seriously though, it is a very useful method that lets you cycle through all the elements of an array forever
unless you give a condition to stop it or put a number in parentheses following .cycle.
Or until you stop it with control-c. In this example we will use break to end it.

Check it out;

months_of_year = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec"]
   months_of_year.cycle do |month|
   puts month
   break if month == "Dec"
end

(output)
Jan
Feb
Mar
Apr
May
June
July
Aug
Sep
Oct
Nov
Dec

Also, you could put a number in parentheses following .cycle to iterate through it that number of times.
For example;

rainbow = ["Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"]
   rainbow.cycle(2) do |colors|
   puts colors
end

(output)
Red
Orange
Yellow
Green
Blue
Indigo
Violet
Red
Orange
Yellow
Green
Blue
Indigo
Violet

You can also chain it together with other methods for example, you could reverse it.

rainbow = ["Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"]
   rainbow.reverse_each.cycle(1) do |colors|
   puts colors
end

(output)
Violet
Indigo
Blue
Green
Yellow
Orange
Red

.cycle with hashes

It can also be used with hashes.

zodiac = {
   :76 => "Dragon", :77 => "Snake", :78 => "Horse", :79 => "Goat",
   :80 => "Monkey", :81 => "Rooster", :82 => "Dog", :83 => "Pig",
   :84 => "Rat", :85 => "Ox", :86 => "Tiger", :87 => "Rabbit"
}

zodiac.cycle do |year, animal|
   puts "Year: #{year} - Animal: #{animal}"
   break if year == :87
end

(output)
"Year: 76 - Animal: Dragon"
"Year: 77 - Animal: Snake"
"Year: 78 - Animal: Horse"
"Year: 79 - Animal: Goat"
"Year: 80 - Animal: Monkey"
"Year: 81 - Animal: Rooster"
"Year: 82 - Animal: Dog"
"Year: 83 - Animal: Pig"
"Year: 84 - Animal: Rat"
"Year: 85 - Animal: Ox"
"Year: 86 - Animal: Tiger"
"Year: 87 - Animal: Rabbit"


Resources

ruby-doc.org

API Dock

Global Nerdy

sitepoint