Sometimes I found myself need to open a file, read it content and do some functional manipulation and store the data to an variable. This would end up with the following line of code:
@some_vars = File.open("items.txt").read.chomp!.split(',')
I have two questions here:
- Does the File instance
File.open()closed after this line? - How to close such a File instance without sacrificing the readability?
No,
File.openleaves the file handle open. You should useIO.readinstead, which returns the entire contents of the file and closes it when it’s done:This is bit shorter for one-liners than passing a block to
File.open.