Cycling enumerators

805 views

What's the return value of the following Ruby code?

toggler = %w(start stop).cycle

toggler.next
toggler.next

toggler.next # => ???

The correct answer is

nil

"stop"

"start"

It raises IndexError

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

Explanation

The above Ruby code initializes a variable named toggler and assigns it the result of the cycle method applied to an array of two strings: "start" and "stop".

The cycle method is used to create an enumerator that infinitely repeats the elements of the array.

toggler = %w(start stop).cycle

In the next few lines, the next method is called on the toggler object multiple times.

toggler.next
toggler.next

Each time next is called, it advances the enumerator to the next element in the cycle.

In this case, the array ["start", "stop"] is cycled through twice.

After the third call to next, it reaches the first element ("start") again, as the cycle method ensures a continuous looping through the array.

toggler.next # => "start"

Here, it confirms that the third call to next returns the string "start".

Voilà!

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

RubyCademy ©