For this blog post I will be talking about Enumerbale#cycle, first we should go over what Enumerable is. Enumerable provides a set of methods to traverse, search, sort and manipulate collections. Basically it’s loops, arrays, and hashes but you learn to do more with prettier and less lines of code. What Enumberable#cycle does is that it calls block for each element until the however long you set it. If not parameter is set it will go on forever until none or nil is given. #cycle saves elements in an internal array so changes to enum after the first pass have no effects.
a = ["a", "b", "c"] a.cycle { |x| puts x } # print, a, b, c, a, b, c,.. forever. a.cycle(2) { |x| puts x } # print, a, b, c, a, b, c.
There you see that if you put cycle(2) it will only repeat the array two times. But it if doesn't have any limit like a.cycle then it will continue to go on forever. Passing an argument to cycle will completely iterate through the collection that many times. The argument to #cycle specifics the number of times to cycle, not the number of elements to cycle through.