0
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?

Prashanth Chandra
  • 2,672
  • 3
  • 24
  • 42
  • while the answer is technically correct for your usage `File.read(txt)` or `File.open(txt,&:read)` are both self closing. This means you can open and read the file without having to ensure that it closed afterwards. – engineersmnky Apr 15 '15 at 13:17
  • @engineersmnky I never saw this syntax `File.open(txt,&:read)` :D – Arup Rakshit Apr 15 '15 at 13:59
  • @engineersmnky According to this http://stackoverflow.com/questions/5545068/what-are-all-the-common-ways-to-read-a-file-in-ruby, Only File.open(txt,&:read) is self-closing, File.read(txt) isn't. The open method has to be passed a block for it to be self-closing – Prashanth Chandra Apr 16 '15 at 02:55
  • @Coolshanth according to the Official Docs on [File#read](http://ruby-doc.org/core-2.0.0/IO.html#method-c-read). **Opens the file, optionally seeks to the given offset, then returns length bytes (defaulting to the rest of the file). read ensures the file is closed before returning.**. – engineersmnky Apr 16 '15 at 13:11

1 Answers1

5

You need to call close on the file object:

txt.close
fiskeben
  • 3,395
  • 4
  • 31
  • 35