Open In App

Ruby | Enumerable cycle() function

Last Updated : 18 Dec, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

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)

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads