1

我有这个 Ruby 脚本可以将我的 Word 文档转换为 .txt 格式。它工作正常,可以相互转换多个文件,但有时会出现错误。我如何让脚本继续下一个文件,跳过给出错误的文件?请不要对使用其他技术提出任何建议,我对这个很满意。

require 'win32ole'

wdFormatDOSText = 4

word = WIN32OLE.new('Word.Application')
word.visible = false

begin
  ARGV.each do|file|
    myFile = word.documents.open(file)
    new_file = file.rpartition('.').first + ".txt"
    word.ActiveDocument.SaveAs new_file, wdFormatDOSText
    puts new_file
    word.activedocument.close(false) # no save dialog, just close it
  end
rescue WIN32OLERuntimeError => e
  puts e.message
  puts e.backtrace.inspect
  sleep 30
ensure
  word.quit
end
sleep 3
4

1 回答 1

1

迭代集合时,您可以begin...rescue...end在每次迭代开始时启动一个新块并next在救援块内调用:

[ "puts 'hello'", "raise '!'" , "puts 'world'" ].each do |str|
  begin
    eval str
  rescue
    puts "caught an error, moving on"
    next
  end
end

# => hello
# => caught an error, moving on
# => world

所以在你的情况下,它可能看起来像这样:

ARGV.each do |file|
  begin
    # ...
  rescue WIN32OLERuntimeError => e
    puts e.message
    next
  end
end
于 2012-11-10T01:15:52.040 回答