Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

file

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?

like image 967
dj199008 Avatar asked Dec 12 '25 03:12

dj199008


1 Answers

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.

like image 167
Marek Lipka Avatar answered Dec 13 '25 17:12

Marek Lipka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!