File.open(filename).each {|line| print line}

I’m thinking about these two codes:

File.open(filename) do |f|
f.each {|line| print line}
end

and

File.open(filename).each {|line| print line}

The 1st one, f will be automatically closed. But the 2nd one, I don’t
know whether a filehandle created by “File.open” will be closed after
the “each” method has done?

Nope. Another option:

IO.foreach(‘text.txt’) do |line|
print line
end

Joey Z. wrote in post #1009075:

I’m thinking about these two codes:

File.open(filename) do |f|
f.each {|line| print line}
end

and

File.open(filename).each {|line| print line}

The 1st one, f will be automatically closed. But the 2nd one, I don’t
know whether a filehandle created by “File.open” will be closed after
the “each” method has done?

It won’t immediately. However, since you are not storing a reference to
the File object anyhere, the object will probably be garbage-collected
at some future point in the program’s execution, and at that point its
finalizer will be called and the file will be closed.

I say “probably” because ruby’s garbage collector is conservative: if it
sees a value on the stack that looks like an object reference it will
treat that object as in use, even if it isn’t.

If you want to experiment, try

ObjectSpace.each_object(File) { |o| puts o.inspect }