Skip to content
Related Articles

Related Articles

Ruby | Enumerable cycle() function
  • Last Updated : 18 Dec, 2019
GeeksforGeeks - Summer Carnival Banner

The cycle() of enumerable is an inbuilt method in Ruby calls block for each element of enum repeatedly the given numbers times or forever if none or nil is given. If a negative numbers is given or the collection is empty, it does nothing. It returns nil if the loop has finished without getting interrupted. In case no block is given, an enumerator is returned instead.

Syntax: block.cycle(times) { |obj| block }

Parameters: The function takes the block according to which the every block is to be returned. Also it takes the times which signifies the number of times it has to be executed. If times is not given it executes infinitely.

Return Value: It returns the enumerator N times which satisfies the given condition of the block.

Example 1:






# Ruby program for cycle method in Enumerable
  
# Initialize
enu = [12, 18]
  
# returns cycle
res = enu.cycle(3) { |el| puts el*4 }

Output:

48
72
48
72
48
72

Example 2:




# Ruby program for cycle method in Enumerable
  
# Initialize
enu = [12, 18]
  
# returns cycle
res = enu.cycle(3)

Output:

Enumerator: [12, 18]:cycle(3)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :