【发布时间】:2015-09-06 05:25:52
【问题描述】:
此脚本旨在从一个文件中获取数据并将其复制到另一个文件中。 Learn Ruby The Hard Way 对我提出了挑战,要求我编写一个单行代码,所以:
from_file, to_file = ARGV
output = open(to_file, 'w').write(File.read(from_file))
output.close
我在终端中输入ruby ex17.rb test.txt new_file.txt 并得到错误:
undefined method `close' for "new_file.txt":String (NoMethodError)
我无法使用脚本关闭任何文件。如果我将所有方法 open、write 和 read 分开,我可以毫无问题地关闭事物。我读到File.read 会自动关闭一个文件,但我只在读from_file。 to_file 不是还开着吗?
一些文档使用File.open(),但我发现没有必要,Learning Ruby The Hard Way 也不建议使用它,添加File. 来打开文件。 open(filename) 似乎可以自己工作。但是对于read,似乎有必要写File.read。为什么会与用法不一致?
【问题讨论】:
-
File.read是否自动关闭文件取决于你是否使用块。