关于我在代码中明确打开的文件是多么必要的想法,只是一些想法.我来自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)
除非您使用类似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