Ruby | Enumerable cycle() function
Last Updated :
18 Dec, 2019
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:
enu = [ 12 , 18 ]
res = enu.cycle( 3 ) { |el| puts el* 4 }
|
Output:
48
72
48
72
48
72
Example 2:
enu = [ 12 , 18 ]
res = enu.cycle( 3 )
|
Output:
Enumerator: [12, 18]:cycle(3)
Share your thoughts in the comments
Please Login to comment...