Christopher Lawless
Christopher Lawless

Reputation: 1087

Does a ruby loop reading a file close the file afterwards?

Does opening a file with block close it afterwards?

File.open('test.txt') do |txt|
  ...
end

I want to know whether this file is closed at the end of this piece of code or whether I should still be calling:

File.close()

Upvotes: 1

Views: 803

Answers (2)

hirolau
hirolau

Reputation: 13901

An alternative if you want to read the entire file:

my_data = File.read('my_file.txt')

Upvotes: 1

Arup Rakshit
Arup Rakshit

Reputation: 118261

What i want to know is is this file closed at the end of this piece of code or should i still be calling:

Yes it is closed.IO::open says

With no associated block, IO.open is a synonym for ::new. If the optional code block is given, it will be passed io as an argument, and the IO object will automatically be closed when the block terminates. In this instance, ::open returns the value of the block.

f = File.open('doc.txt') do |file|
  file
end

f.closed? # => true

or should i still be calling: File.close() ?

Yes you can,if your block return the file object,before terminating,like my above code.Or if you assign the file object inside a block to a local variable as below :

f = nil
File.open('doc.txt') do |file|
  f = file
  # your code
end

f.closed? # => true

Upvotes: 5

Related Questions