Array#cycle() : cycle() is a Array class method which returns the array by calling the given block each time for every element in the array ‘n’ no. of times and if ‘nil’ is given, then it will call it for forever.
Syntax: Array.cycle()
Parameter:
block – condition
n – number of times to call the block
Return: array by calling the given block each time for every element in the array ‘n’ no. of times
Code #1 : Example for cycle() method
a = [ 18 , 22 , 33 , 5 , 6 ]
b = [ 1 , 4 , 1 , 1 , 88 , 9 ]
c = [ 18 , 22 , nil , nil , 50 , 6 ]
puts "cycle : #{a.cycle(3){ |x| puts x*x }}\n\n"
puts "cycle : #{b.cycle(2){|x| puts x}}\n\n"
|
Output :
324
484
1089
25
36
324
484
1089
25
36
324
484
1089
25
36
cycle :
1
4
1
1
88
9
1
4
1
1
88
9
cycle :
Code #2 : Example for cycle() method
a = [ "abc" , "nil" , "dog" ]
b = [ "cow" , "1" , "dog" ]
puts "cycle : #{a.cycle(3){ |x| puts x }}\n\n"
puts "cycle : #{b.cycle(-1){|x| puts x}}\n\n"
|
Output :
abc
nil
dog
abc
nil
dog
abc
nil
dog
cycle :
cycle :
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!