The Cycle Method

How to cycle through arrays

July 30, 2014


The cycle method in ruby infinitely calls a block for each element in a collection.

Take array a for example:

a = [“a, b, c”]

When you apply the cycle method to the array and you apply a block, the cycle function passes each item into the block. cycle will continue to go through the array forever unless it encounters a break statement in the block.

a.cycle {|a| puts a}  =>  a, b, c, a, b, c, a, b, c …. 

If you want to stop the cycle after a certain number of well… cycles. Then you must state that when declaring the method.

a.cycle(4) {|a| puts a } => a, b, c, a, b, c, a, b, c, a, b, c

A more real world example of this is as follows:


sandwich_array = [“Po Boy”,  “PB&J”, “BLT”, “Reuben”, “Grilled Cheese”, “Tuna”]
sandwich_array.cycle {|sandwich| puts sandwich}

=>	Po Boy
	PB&J 
	BLT
	Reuben
	Grilled Cheese 
	Tuna
					

In order to break this within the cycle you can use do and declare a certain break point. Example:


sandwich_array.cycle do |sandwich|
	puts sandwich
	break if sandwich == “Reuben”
end

=>	Po Boy
	PB & J
	BLT
	Reuben

=>	Nil

While doing looking up the practical uses of the cycle method, I came across this really cool everyday use case for it. In this case, one can use the cycle to create multiple enumerators to assign meals to a particular chef each of days.


# Create an enumerator for days

days = %w{Monday Tuesday Wednesday Thursday Friday Saturday Sunday}.cycle

=> #

# Create an enumerator for dinners

dinners = ["Jerk chicken", "Lamb vindaloo", "Chicken fried steak", "Yeung Chow fried rice", "Tonkatsu", "Coq au Vin", "Chunky bacon", "Pierogies", "Salisbury steak", "Bibim Bap", "Roast beef", "Souvlaki"].cycle

=> #

# Create an enumerator for chefs

chefs = [“Wolfgang Puck”, “Rachel Ray”, “Julia Childs”, “Martha Stewart”, “Anthony Bourdain”, “The Pioneer Woman”, “The Iron Chef”]

# Let's assign dinner-cooking duties to the crew!

# We can use the .next function when using the cycle in order to cycle to the next item in the list and breaks there before being called to move on again.

10.times do
	day = days.next
	dinner = dinners.next
	chef = chefs.next[1]
	puts "On #{day}, #{chef} will prepare #{dinner}."
end
=>	On Monday, Wolfgang Puck will prepare Jerk chicken.
	On Tuesday, Rachel Ray will prepare Lamb vindaloo.
	On Wednesday, Julia Childs will prepare Chicken fried steak.
	On Thursday, Martha Stewart will prepare Yeung Chow fried rice.
	On Friday, Anthony Bourdain will prepare Tonkatsu.
	On Saturday, The Pioneer Woman will prepare Coq au Vin.
	On Sunday, The Iron Chef will prepare Chunky bacon.
	On Monday, Wolfgang Puck will prepare Pierogies.
	On Tuesday, Rachel Ray will prepare Salisbury steak.
	On Wednesday, Julia Childs will prepare Bibim Bap.