Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Foundations Loops Control Flow

Taylor Plante
Taylor Plante
22,283 Points

Not getting looping effect in video

The goal is to have the loop repeat every time it reaches 'horse' until 10 items have been listed. Here is the error I'm getting when typing ruby loops-11.rb in my console:

*****-MacBook-Pro:loops taylorplante$ ruby loops-11.rb loops-11.rb:8: Invalid retry loops-11.rb: compile error (SyntaxError)

Here is my code in loops-11.rb, copied exactly from the video as far as I know:

animals = %w(dog cat horse goat snake frog)
count = 0

for animal in animals
    puts "The current animal is #{animal}"
    break if count == 10
    count += 1
    retry if animal == 'horse'
end

3 Answers

Sreng Hong
Sreng Hong
15,083 Points

Hi Taylor,

I got an unexpected error like you too. I've watched through that course, but I didn't realize that it's an error.

I'm not so sure what the problem are, but I try to find out in Ruby Doc and i think Retry should be use with Rescue.

I try to write the code that have the same output as this one and it looks like this:

animals = %w(dog cat horse goat snake frog)
count = 0

begin
    for animal in animals
        puts "The current animal is #{animal}"
        break if count == 10
        count += 1
        if animal == 'horse'
            raise
        end
    end
rescue
    retry
end

Tell me what you think about it.

Taylor Plante
Taylor Plante
22,283 Points

Good stuff! Thanks. Yeah he does another command similar to reply directly after and that one worked fine, not sure what the deal is there...

Antoine Boillot
Antoine Boillot
10,466 Points

Hi all,

Fyi, I found that statement...

"Inside a rescue block is the only valid location for retry, all other uses will raise a SyntaxError."

...Here.

Look like the Begin/Rescue block is indeed the only way to use Retry.

Thanks a lot Sreng Hong.