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.
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.
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.
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.
ar = ["apple", "orange"]
n = 4
n.times { ar.each{|a| p a} }
array = ["apple", "orange"]
numOfIteration=4
for i in 0..numOfIteration-1
puts array[i%array.size]
end
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With