Ruby | Array cycle() operation

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



filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby code for cycle() method
  
# declaring array
a = [18, 22, 33, 5, 6]
  
# declaring array
b = [1, 4, 1, 1, 88, 9]
  
# declaring array
c = [18, 22, nil, nil, 50, 6]
  
# cycling the array elements
puts "cycle : #{a.cycle(3){ |x| puts x*x }}\n\n"
  
# cycling the array elements
puts "cycle : #{b.cycle(2){|x| puts x}}\n\n"

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby code for cycle() method
  
# declaring array
a = ["abc", "nil", "dog"]
  
# declaring array
b = ["cow", "1", "dog"]
  
# cycling the array elements
puts "cycle : #{a.cycle(3){ |x| puts x }}\n\n"
  
# cycling the array elements
# passing negative value for cycle
puts "cycle : #{b.cycle(-1){|x| puts x}}\n\n"

chevron_right


Output :

abc
nil
dog
abc
nil
dog
abc
nil
dog
cycle : 

cycle : 



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.