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

Viewed 917
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.

5 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.

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

another non-idiomatic for loop, 3 dots removes need for explicit subtraction

array = ['apple', 'orange']
number = 4

for i in 0...number
  puts array[i % array.size]
end

and some silliness with lambdas and recursion :D

array = ['apple', 'orange']
number = 4

loop = lambda do |list, count|
  return if count == number

  puts list[count % list.size]

  loop.(list, count + 1)
end

loop.(array, 0)

Related