1

Given the following code:

file = File.new('file1.txt', 'w')
# write data to the file
file.close

What does it mean when you decide to open a file in Ruby using the File.new method call. I understand that file = File.new, creates if not created, the file1.txt, and writes at the very beginning, but nothing is happening from an OS perspective. It simply gets created, and can be accessed later, through a text editor, or through the Ruby prompt. No file gets opened via a text editor or anything.

Subsequently it must be closed, So I don't understand how you can close the file, when nothing really gets opened from an OS perspective.

Can someone shed light on how the file is "opened", and then subsequently "closed"?

the12
  • 2,395
  • 5
  • 19
  • 37
  • Although it's not Ruby specific, take a look and see if the answers to [this existing question](http://stackoverflow.com/questions/33495283/what-does-opening-a-file-actually-do) are helpful. – mikej Oct 21 '16 at 20:04
  • I don't understand. You say that "It simply gets created, and can be accessed later, through a text editor, or through the Ruby prompt." and that "nothing really gets opened from an OS perspective.". You also have the `# write data to the file` comment in your code but how can you write data to a file when "nothing really gets opened"? `File.new` does open the file (after creating it if necessary), that's why you can write to it. – mu is too short Oct 21 '16 at 20:04
  • To be more specific, where does it get opened? It is not appearing on my OS at all (any active program, atleast that I can see from my taskbar, using Windows if that helps). – the12 Oct 21 '16 at 20:06

1 Answers1

2

The File.new method executes a call to IO::new (docs here).

The thing being "opened" in this case is an input/output stream which Ruby tracks using file descriptors. These file descriptors can be expensive to keep around which is why its good practice to call the close method on any instances of File or IO.

AJ Gregory
  • 1,589
  • 18
  • 25