【问题标题】:Learn Ruby The Hard Way: Undefined method `close'艰难地学习 Ruby:未定义的方法 `close'
【发布时间】: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)

我无法使用脚本关闭任何文件。如果我将所有方法 openwriteread 分开,我可以毫无问题地关闭事物。我读到File.read 会自动关闭一个文件,但我只在读from_fileto_file 不是还开着吗?

一些文档使用File.open(),但我发现没有必要,Learning Ruby The Hard Way 也不建议使用它,添加File. 来打开文件。 open(filename) 似乎可以自己工作。但是对于read,似乎有必要写File.read。为什么会与用法不一致?

【问题讨论】:

  • File.read 是否自动关闭文件取决于你是否使用块。

标签: ruby methods


【解决方案1】:

IO#write 返回写入的字节数,因此,您不能在其上调用close

如果你需要单线解决方案,你可以试试

open(to_file, 'w') { |f| f.write (File.read(from_file)) }

[IO#open][2] 将在块执行后关闭流,不需要显式的close。 同样,IO#read 在文件被完全读取后关闭流,不需要显式的close

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 2013-04-06
    • 2011-12-04
    • 2016-06-28
    • 1970-01-01
    相关资源
    最近更新 更多