Thanks, but I am afraid I wasn't that clever this time:
$ irb19 -r open-uri
Ruby version 1.9.3
irb(main):001:0> url = 'http://www.google.com/'
=> "http://www.google.com/"
irb(main):002:0> io = open url
=> #<File:/tmp/open-uri20120314-2280-ju7rp9>
irb(main):003:0> io.read.length
=> 12080
irb(main):004:0> io.close
=> nil
irb(main):005:0> io = File.open url
Errno::ENOENT: No such file or directory - http://www.google.com/
from (irb):5:in `initialize'
from (irb):5:in `open'
from (irb):5
from /opt/bin/irb19:12:in `<main>'
irb(main):006:0> File.read(url).length
Errno::ENOENT: No such file or directory - http://www.google.com/
from (irb):6:in `read'
from (irb):6
from /opt/bin/irb19:12:in `<main>'
Should've tested this properly. :-))
Sorry for the confusion.
But we can do
irb(main):012:0> def read(x)
irb(main):013:1> io = open(x)
irb(main):014:1> begin
irb(main):015:2* io.read
irb(main):016:2> ensure
irb(main):017:2* io.close
irb(main):018:2> end
irb(main):019:1> end
=> nil
irb(main):020:0> read(url).length
=> 11117
While we're at it we could also do
irb(main):022:0> class Object
irb(main):023:1> def tap_close
irb(main):024:2> yield self
irb(main):025:2> ensure
irb(main):026:2* close
irb(main):027:2> end
irb(main):028:1> end
=> nil
irb(main):029:0> open(url).tap_close {|io| io.read}.length
=> 11117
or
irb(main):030:0> def auto_close(x)
irb(main):031:1> yield x
irb(main):032:1> ensure
irb(main):033:1* x.close
irb(main):034:1> end
=> nil
irb(main):035:0> auto_close(open(url)) {|io| io.read}.length
=> 11105
Hmm, I think I like the variant with #read best.
Kind regards
robert
···
On Tue, Mar 13, 2012 at 9:08 PM, Wayne Brisette <wbrisett@att.net> wrote: