Reputation: 2415
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"?
Upvotes: 1
Views: 503
Reputation: 1609
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
.
Upvotes: 2