the12 the12 - 1 month ago 12
Ruby Question

What does it mean to "open" a file in Ruby by using File.new?

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

Answer

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.