Brandon
Brandon

Reputation: 1751

Ruby Restart Array Loop

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!

Upvotes: 2

Views: 1201

Answers (4)

Cary Swoveland
Cary Swoveland

Reputation: 110725

(0..Float::INFINITY).each do |i|
  puts letters[i % letters.size] 
  puts "Whew! That was the last letter, so it's time to start over." \
    if ((i+1) %letters.size).zero?
end
  # A
  # B
  # C
  # Whew! That was the last letter, so it's time to start over.
  # A
  # B
  # C
  # Whew! That was the last letter, so it's time to start over.
  # A
  # B
  # ...

Upvotes: 3

Agush
Agush

Reputation: 5116

From Ruby1.9 retry can only be used inside a begin/rescue block

What you are trying to do can be done like this:

letters = ["A","B","C"]
begin
  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)
      raise
    end
  end
rescue
  sleep 1
  retry
end

Take note of the raise keyword after the comment which causes the code to go into rescue and then sleep and retry

Another option would be to use cycle which is more clean and elegant

Upvotes: 2

sawa
sawa

Reputation: 168199

Use cycle.

letters.cycle do |letter|
  ...
end

Upvotes: 7

Stefan
Stefan

Reputation: 114218

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

Upvotes: 5

Related Questions