Home »
Ruby Tutorial
Ruby Array.cycle() Method
By IncludeHelp Last updated : December 01, 2024
In this article, we will study about Array.cycle() method. You must be a little more excited to read about Array.cycle method due to its catchy name as I was pretty amazed after reading this method. In the upcoming content, we will see the way through which we can implement this method. We will understand it with the help of its syntax and demonstrating examples.
Description and Usage
This method is specially defined for the Array class in Ruby's library. This method is one of the examples of Array instance methods. It works like a loop and calls or invokes the given block for each element of Array instance for n number of times. This method will not work if you do not provide any positive number. If you are not providing anything then it may result in the infinite repetition of the elements of the object of Array class. The return type of this method is "nil" and it does not undergo any change in the actual elements of Array objects. This method can be considered as one of the examples of non-destructive methods present in the Rich Ruby library.
Syntax
cycle(n=nil) { |obj| block } -> nil
Parameters
This method requires one positive number and if nothing is passed then you have to encounter an infinite loop.
Example 1
=begin
Ruby program to demonstrate cycle method
=end
# array declaration
array1 = ["1","Ramesh","Apple","12","Sana","Yogita","Satyam","Harish"]
puts "Array cycle implementation."
array1.cycle(3){|x| puts x}
Output
Array cycle implementation.
1
Ramesh
Apple
12
Sana
Yogita
Satyam
Harish
1
Ramesh
Apple
12
Sana
Yogita
Satyam
Harish
1
Ramesh
Apple
12
Sana
Yogita
Satyam
Harish
Explanation
In the above code, you will observe that each element of the Array instance have been repeated three times and the repetition is not random, it is going in a proper sequence as stored inside the instance of Array class with which the method is invoked.
Example 2
=begin
Ruby program to demonstrate cycle method
=end
# array declaration
array1 = ["1","Ramesh","Apple","12","Sana","Yogita","Satyam","Harish"]
puts "Array cycle implementation."
array1.cycle{|x| puts x}
Output
Array cycle implementation.
1
Ramesh
Apple
12
Sana
Yogita
Satyam
Harish
1
Ramesh
Apple
12
Sana
Yogita
Satyam
Harish
1
Ramesh
Apple
12
Sana
Yogita
Satyam
Harish
1
Ramesh
Apple
12
.
.
.
.
Infinite loop...
Explanation
When you will run the above code, you will observe that it will result in an infinite loop. This has happened because you are not passing any argument or positive number with the method.