dj199008
dj199008

Reputation: 1789

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

Suppose two kinds of ruby File operations.

Firstly,

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

Secondly,

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

It's known to all that we should close file after we finish using it. But, in the second block of code, Ruby interpreter throw an error message shown below:

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

I need not to use file.close in the second case? I wonder why?

Upvotes: 3

Views: 747

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118261

Marek Lipka answered correctly, I just wanted you to point to the documentation sentences again.

I need not to use file.close in the second case?

You don't need to do so.

Read the doc IO::read carefully :

Opens the file, optionally seeks to the given offset, then returns length bytes (defaulting to the rest of the file). read ensures the file is closed before returning.

Upvotes: 3

Marek Lipka
Marek Lipka

Reputation: 51151

It's because File.read method returns string with content of the file, not the File object. And yes, you don't need to use close explicitly if you use File.read method, because ruby does it for you automatically.

Upvotes: 5

Related Questions