Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


What is array.cycle() in Ruby?

okwudili onyejiaku


array.cycle() is a method which returns an array by calling the given block passed to this method for each element. It is either called n times according to the parameter, or it is called infinitely many times if nil or no parameter is given. If a non-positive number is given in the block or the array is empty, then nothing will be done by this method.

If everything goes fine and the loop has finished, then a nil or nothing is returned. If no block is given, an Enumerator is returned.


array.cycle(n=nil){|obj| block} 


n: This is the number of times the block should run.

obj: this is the representation of each element of the array.

block: this is the condition

Return value

It returns an array by calling the given block n times or infinitely many if no parameter is given.

Code example

In the example below, we will demonstrate the use of the cycle() method.

# create arrays
arr1 = [1, 2, 3, 4, 5]

# call the cycle method
a = arr1.cycle(2){|x| puts x}

puts "#{a}"

In the code above, we made the block execute twice. For every time it loops, it should print out the elements of the arr1 array.

Here is another example. This will loop forever and never finish, because a nil is given.

# create array
arr2 = ["a", "b", "c"]

# cycle the array forever
b = arr2.cycle(nil){|x| puts x}

puts b

When we run the code above, we see that it loops forever because a nil is passed.

In the example below, we will demonstrate the use of the cycle() method without passing a block. Also, as we mentioned earlier, an Enumerator will be returned.

# creat an array
arr3 = ["Meta", "Google", "Amazon"]

# cycle array without block
c = arr3.cycle(3) 

# print out returned value
puts c



View all Courses

Keep Exploring