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
It returns an array by calling the given block n
times or infinitely many if no parameter is given.
In the example below, we will demonstrate the use of the cycle()
method.
# create arraysarr1 = [1, 2, 3, 4, 5]# call the cycle methoda = 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 arrayarr2 = ["a", "b", "c"]# cycle the array foreverb = 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 arrayarr3 = ["Meta", "Google", "Amazon"]# cycle array without blockc = arr3.cycle(3)# print out returned valueputs c