不关闭此代码段中的文件是不好的做法吗?

sta*_*tor 0 ruby file-io

关于我在代码中明确打开的文件是多么必要的想法,只是一些想法.我来自C和C++编程的背景,并开始通过Ruby导航.提前感谢您的反馈.

from_file, to_file = ARGV
script = $0

puts "Copying from #{from_file} to #{to_file}"
File.open(to_file, 'w').write(File.open(from_file).read())

puts "Alright, all done."
Run Code Online (Sandbox Code Playgroud)

Thi*_*ter 6

除非您使用类似withpython中的语句,否则不关闭文件总是不好的做法.

虽然脚本语言通常会在退出时关闭打开的文件,但是一旦完成文件就会更清楚 - 特别是在写入文件时.

显然 Ruby有类似于python的东西with:

File.open(from_file, 'r') do |f_in|
    File.open(to_file, 'w') do |f_out|
        f_out.write(f_in.read)
    end
end
Run Code Online (Sandbox Code Playgroud)

相关文档:http://ruby-doc.org/core-1.9.3/File.html#method-c-open

  • @stanigator:为什么你关心(甚至一点点)添加几行代码,如果这会提高你的代码质量? (4认同)
  • @stanigator不,这里的`do ... end`是一个*block*,传递给`open`方法,然后打开文件,然后运行块作为参数传递文件,当块完成时运行它然后关闭文件. (2认同)