From: Bertram Scharpf Date: 2007-07-10T22:10:47+09:00 Subject: Re: Method to prevent writing over a file Hi, Am Dienstag, 10. Jul 2007, 22:03:52 +0900 schrieb Bertram Scharpf: > > def safe_open name > i = 0 > n = name > begin > f = File.new n, File::CREAT|File::EXCL|File::WRONLY > yield f > rescue Errno::EEXIST > i += 1 > n = "#{name}_#{i}" > retry > ensure > f.close > end > end Sorry, this is wrong. The yield should _not_ appear inside the begin-rescue block as it could raise an exception itself. Better is: def safe_open name i, n = 0, name f = begin File.new n, File::CREAT|File::EXCL|File::WRONLY rescue Errno::EEXIST i += 1 n = "#{name}_#{i}" retry end yield f ensure f.close end Bertram -- Bertram Scharpf Stuttgart, Deutschland/Germany http://www.bertram-scharpf.de