Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Restart Array Loop

Tags:

arrays

ruby

I am trying to restart an array loop in ruby once the entire array has been iterated through.

I've found that the retry method will not work for this. Code below:

letters = ["A","B","C"]

letters.each do |letter|
  puts letter
  if letter == letters.last
    puts "that was the last letter"
    #restart the array from A again (I'd like it to continue looping infinitely)
  end
  sleep 1
end

Any ideas would be greatly appreciated. Thank you!

like image 451
Brandon Avatar asked Apr 25 '26 01:04

Brandon


2 Answers

Use cycle.

letters.cycle do |letter|
  ...
end
like image 54
sawa Avatar answered Apr 27 '26 13:04

sawa


Just put your each loop into another loop:

loop do
  letters.each do |letter|
    puts letter
    sleep 1
  end
  puts "that was the last letter"
end
like image 36
Stefan Avatar answered Apr 27 '26 14:04

Stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!