确保在Ruby中关闭文件,并进行救援并确保

Hom*_*ith 0 ruby file

我有以下代码:

begin
   @output_file = File.open("output.txt", "w")
   File.read(@input_file).each_line do |line|
   taxify_line(line)
end
rescue => e
   p "Smz went wrong..."
end
@output_file.write("Last line of output")
@output_file.close unless @output_file.nil?
Run Code Online (Sandbox Code Playgroud)

确保无论何时捕获异常,两个文件(@input_file和@output_file)都关闭的正确方法是什么?

Ser*_*sev 5

rescue子句应该在begin..end块内.还有,令人惊讶的是,ensure条款完全符合您的想法

begin
   @output_file = File.open("output.txt", "w")
   File.read(@input_file).each_line do |line|
     taxify_line(line)
   end
rescue => e
   p "Smz went wrong..."
ensure
  @output_file.write("Last line of output")
  @output_file.close unless @output_file.nil?
end
Run Code Online (Sandbox Code Playgroud)

  • 我在实用编程红宝石书中阅读了以下内容;并变得有些困惑。有人可以澄清这一点吗: #start_of_code f = File.open("testfile") begin # .. processrescue # ..handle error Ensure f.close end #end_of_code "初学者通常会犯这样的错误:将 File.open 放入文件中在 begin 块内。在这种情况下,这是不正确的,因为 open 本身会引发异常。如果发生这种情况,您将不希望运行 Ensure 块中的代码,因为没有文件可供访问关闭。” (2认同)