Phase 0 - Week 4 The Hills are Alive with Enumerables
Friday, May 22, 2015
Being able to iterate over a collection of data is critical and Ruby provides a very clean and easy to implement method for doing this without the need to keep track of counters and/or indices's. The Enumerable #cycle provides a clean way to iterate through an array infinitely or x number of times and perform {A Block of Code}. If a block of code is not passed, #cycle will return an enumerator that can be controlled with other Enumerable like #next.
Now it is time for Maria to bring the Von Trapp children into the 21st Century. By using the Enumerable #cycle, Maria can easily and efficiently make sure the Von Trapps know all of the notes. If today's lesson requires them to practice the notes 10 times each, a simple #cycle(10) does the trick. But what if Maria needs even more time up on the hill twirling, all she needs to do is leave off the (10) and the Von Trapps will be stuck in infinite practice. After she has the basic notes down, Maria can start using Hashes to really expand her lessons and then she can use some of her free time to sew new outfits from more modern curtains.
Unfortunately, we will have to look into Hashes in another Blog, today we will use #cycle to iterate over Maria's array. In the The Enumerable #cycle box below, the first example passes the value (2) to #cycle and it iterates through the array two times. In the second example, we do not pass a value and #cycle continues to iterate through infinitely.
The Enumerable #cycle
In the example below, the #cycle Enumerable is used without a code block, which returns a enumerator that can be combined with other methods like #next which allows you to iterate through the elements one at a time. The first step is to run #cycle without a code block on the sound_of_music_array and assign the enumerator that is retuned to the variable cycle.enum. Now cycle.enum.next can be used to quickly cycle through the items in the array one at a time.
Cycle Enumerator #next
As you can see, Enumerables and Enumerators can give you a great deal of flexibility when working with collections of data. The #cycle and #next are just a couple of the Enumerables that are available to you. Please Download Maria's Lesson Plan to see the Enumerable #cycle hard at work.