2

Rubyで再開をループに書き込むにはどうすればよいですか? これがサンプルコードです。

#!/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

ただし、実行時にRubyはエラーメッセージを返します

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

Ruby 1.9.3 を使用しています。

4

2 に答える 2

4

;retryの代わりに使用する必要があります。nextしかし、これは無限ループを引き起こします(retryの最初から再起動しますbegin

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

項目をスキップして次の項目に進む場合は、ループ内で例外をキャッチします。

a = [1,2,3,4,5]
a.each{|i|
    begin
        puts i
        if  i == 4 then raise StandardError end
    rescue => e
    end
}
于 2014-02-04T02:23:56.960 に答える
2

例外キャッチをeachブロックに移動します。

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
于 2014-02-04T02:24:15.863 に答える