the12 the12 - 3 years ago 110
Ruby Question

What does it mean to "open" a file in Ruby by using

Given the following code:

file ='file1.txt', 'w')
# write data to the file

What does it mean when you decide to open a file in Ruby using the method call. I understand that file =, 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 Source

The 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download