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!

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

Nicholas Lee
Nicholas Lee
12,474 Points

Why is Jason using retry inside a loop?

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'

First it does not work.

loops-11.5.rb:5: Invalid retry loops-11.5.rb: compile error (SyntaxError)

I also read on stackoverflow that, retry is for exceptions, not loops.

Along with this code, why would he put "retry if animal == 'horse' at the bottom. Doesn't it make more sense for it to be at the top?

I also just read in "The Ruby Way" The keyword retry is used in two contexts: in the context of an iterator and in the context of a begin/end blog (exception handling). Within the body of any iterator (or for loop) it will force the iterator to restart, reevaluating any arguments passed to the iterator. Not that it will not work for loops in general (while and until).

1 Answer

Maciej Czuchnowski
Maciej Czuchnowski
36,441 Points

Regarding the "retry if animal == 'horse' at the bottom - I guess he wants to print the "current animal is horse" before the loop is retried.

And it appears you are right - this code should not work for any Ruby version after 1.8 (older tutorials allow it for loops in general because they use Ruby version that allows it). Jason's terminal says he's using 1.9.3, so it's a mystery to me how he managed to run it...i tried it with 2.1.2, 1.9.3 and 1.9.2. Same error.