Question

How can I write resuming into loops in Ruby? Here is a sample code.

#!/usr/bin/ruby
#

a = [1,2,3,4,5]

begin
    a.each{|i|
        puts i
    if( i==4 ) then raise StandardError end # Dummy exception case
    }
rescue =>e
  # Do error handling here
  next # Resume into the next item in 'begin' clause
end

However, when running, Ruby returns the error message

test1.rb:13: Invalid next
test1.rb: compile error (SyntaxError)

I'm using Ruby 1.9.3.

Was it helpful?

Solution

You should use retry instead of next; But this will cause infinite loop (retry restart from the beginning of the begin)

a = [1,2,3,4,5]
begin
    a.each{|i|
        puts i
        if  i == 4 then raise StandardError end
    }
rescue =>e
    retry # <----
end

If you want skip an item, and continue to next item, catch the exception inside the loop.

a = [1,2,3,4,5]
a.each{|i|
    begin
        puts i
        if  i == 4 then raise StandardError end
    rescue => e
    end
}

OTHER TIPS

Move your exception catching into the each block e.g:

a = [1,2,3,4,5]
a.each do |i|
  puts i
  begin
  # Dummy exception case
  if( i==4 ) then raise StandardError end

  rescue =>e
    # Do error handling here
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top