Only that it's a bit verbose:
tf = nil
Tempfile.open(...) do |io|
tf = io
...
end
puts tf.path
No, I was talking about the other version which returns whatever the
block returns. You would do
tf = Tempfile.open(...) do |io|
...
io
end
puts tf.path
Apparently people differ in their preferences.
Maybe that's what the accepted patch does - I haven't tested it. It
would be consistent with File.open { ... } if it worked that way.
Exactly that is what the patch does:
http://redmine.ruby-lang.org/repositories/diff/ruby-19?rev=19454
Anyway, I think we're talking about minutiae. You say that one should
close the file at the earliest opportunity to "save resources", but the
only resource we're talking about is one slot in the kernel file
descriptor table, and most apps aren't going to be constrained by that.
That's true. But I also have seen issues caused by files being opened
more than once by the same process. Plus, you'll notice much faster if
you try to write to the tempfile after you thought you were done when
you close the file. If the code is more complicated these bugs can be
hard to track. How much simpler is it if you see this:
irb(main):006:0> Tempfile.open "x" do |io|
irb(main):007:1* p io
irb(main):008:1> io.puts "hello"
irb(main):009:1> io.close
irb(main):010:1> io.puts "world"
irb(main):011:1> end
#<File:C:/Users/Robert/x20100630-4456-1ixsj0i-0>
IOError: closed stream
from (irb):10:in `block in irb_binding'
from /usr/local/lib/ruby19/1.9.1/tempfile.rb:199:in `open'
from (irb):6
from /usr/local/bin/irb19:12:in `<main>'
It's probably not that big a deal but I believe such discussions bring
benefit to the community by presenting alternative solutions to a
problem along with arguments. I always like this food for thought.
Thanks for sharing your thoughts!
Kind regards
robert