Ruby 中 main:Object 的未定义方法 'close' (NoMethodError)

Undefined method 'close' for main:Object (NoMethodError) in Ruby

filename = ARGV.first

txt = open filename

puts "Here's your file #{filename}:"
print txt.read

puts "Type the filename again: "
file_again = $stdin.gets.chomp

txt_again = open file_again

print txt_again.read

close(txt)
close(txt_again)

程序运行到最后都很好,但在打印第二个文件的内容后立即崩溃并出现标题错误消息。

我检查了 txt,txt_again 使用 (.class) 并确认两者都是文件 objects。为什么不关闭工作?

您需要对文件对象调用close

txt.close