Ruby retry statement

Viewed 213

I am following this tutorial and read until loops. From the tutorial, I expected to get:

Value of local variable is 1
Value of local variable is 2
Value of local variable is 1
Value of local variable is 2
Value of local variable is 1
Value of local variable is 2
............................

but I get this instead

Value of local variable is 0
Value of local variable is 1
Value of local variable is 2

This is the code I use, which exactly same with the tutorial

#!/usr/bin/ruby

for i in 0..5
  retry if i > 2
  puts "Value of local variable is #{i}"
end

Did I miss anything?

2 Answers

As others have stated, retry is limited to rescue blocks now. If you want to re-produce your example, you'll have to wrap it in a begin...rescue:

begin
  for i in 0..5
    raise "too big" if i > 2
    puts "Value of local variable is #{i}"
  end
rescue
  retry
end

You missed this: from The Ruby Programming Language, (a book from 2008, co-authored by Matz, which covers Ruby 1.8 and 1.9):"(...) In Ruby 1.8 however, retry has another use: it starts an iterator based iteration (or any method invocation) from the beginning. This use of the retry statement is extremely rare, and has been removed from the language in Ruby 1.9. It should, therefor, be considered a deprecated language feature and should not be used in new code."(page 152). Running OP's code results in a syntax error, at least since Ruby 2.3. Invalid retry (SyntaxError)

Related