Search code examples
rubyfilefcloselearn-ruby-the-hard-way

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)

The program runs fine till the end, but crashes with the titled error message right after printing the contents of the second file.

I checked the txt, txt_again using (.class) and confirmed that both are File objects. Why isn't close working?


Solution

  • You need to call close on the file object:

    txt.close