An Enumerable method: cycle

01 Nov 2015
Ever wanted to iterate using times?

Cycle is a very simple method, which works a lot like times. I took the example from the Ruby docs for this method and toyed around with it:

a = [ "a", "b", "c" ]
a.cycle( 3 ) { |x| puts x }

# => a
# => b
# => c

That's pretty straightforward, but I wanted to get a little more complicated:

a.cycle( 6 ) { |x| puts x + " thing" }

# => a thing
# => b thing
# => c thing
# First cycle

# => a thing thing
# => b thing thing
# => c thing thing
# Second cycle
...
# => a thing thing thing thing thing thing
# => b thing thing thing thing thing thing
# => c thing thing thing thing thing thing
# Sixth cycle

That's way too many "things" for my liking! While 'times' repeats a block of code a certain number of times, cycle iterates through an object, passing the block to each element, then iterating again until it reaches the number passed to it.

Be careful! If you don't pass an argument to cycle, it will go on forever!

Cycle is very basic, like 'times' for enumerables. I imagine that other other methods may be better for specific instances, but cycle may be good to know for those times when you just need to repeat a code block.

Previous: Arrays and Hashes | Next: Ruby's So Classy