Should I destroy the File object after File.read and File.open in Ruby?

Suppose there are two kinds of ruby ​​file operations.

Firstly,

file = File.open("xxx")
file.close

Secondly,

file = File.read("xxx")
file.close

Everyone knows that we must close the file after we finish it. But in the second block of code, the Ruby interpreter produces the error message shown below:

in `<main>': undefined method `close' for #<String:0x000000022a3a08> (NoMethodError)

I do not need to use file.closein the second case? I wonder why?

+3
source share
2 answers

This is because the method File.readreturns a string with the contents of the file, not File. And yes, you do not need to use it explicitly closeif you use the method File.read, because ruby ​​does this automatically for you.

+5
source

Marek Lipka , , .

file.close ?

.

IO::read:

, , ( ). read , .

+3

All Articles