Reputation: 1789
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
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
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