Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over an array a certain amount of times?

array = [apple, orange]    
number = 4

desired output:

apple    
orange    
apple    
orange

So far, I have:

array.each do |x|
  puts x
end

I'm just not sure how to iterate over the array 4 times.

like image 928
Karen Avatar asked Aug 08 '20 23:08

Karen


People also ask

How do you loop through an array once?

How to Loop Through an Array with a forEach Loop in JavaScript. The array method forEach() loop's through any array, executing a provided function once for each array element in ascending index order. This function is known as a callback function.

How do you cycle through an array?

Iterating over an array You can iterate over an array using for loop or forEach loop. Using the for loop − Instead on printing element by element, you can iterate the index using for loop starting from 0 to length of the array (ArrayName. length) and access elements at each index.


Video Answer


4 Answers

array = ["apple", "orange"]
iter_count = 4
array.cycle.take(iter_count).each { |x|
  puts x
}

array.cycle gives us an infinite enumerable that repeats the elements of array. Then we take the first iter_count elements from it and iterate over that.

Enumerable has a ton of goodies that perform neat tasks like this. Once you familiarize yourself with the module, you'll find you can do a lot of array- and stream- oriented processes much more easily.

like image 94
Silvio Mayolo Avatar answered Oct 17 '22 16:10

Silvio Mayolo


ar = ["apple", "orange"]
n = 4
n.times { ar.each{|a| p a} }
like image 26
Les Nightingill Avatar answered Oct 17 '22 14:10

Les Nightingill


array = ["apple", "orange"]
numOfIteration=4
for i in 0..numOfIteration-1
   puts array[i%array.size]
end
like image 2
Heysem Avatar answered Oct 17 '22 16:10

Heysem


A fun way to achieve this:

4.times { |n| p array[n % array.count] }

Definitely not the best: every iteration we are counting the number of elements in array and also processing that n is dividable by the number of elements. It's also not very readable, as there is some cognitive processing required to understand the statement.

A nicer way to achieve this:

print(arr.cycle.take(4).join("\n"))
apple
orange
apple
orange
like image 1
benjessop Avatar answered Oct 17 '22 16:10

benjessop