Ruby | Enumerable cycle() function

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

48
72
48
72
48
72

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.