From: Jason Voegele Date: 2003-04-02T00:40:21+09:00 Subject: Re: Opera bookmark cleaner. Brian Candler wrote: >On Tue, Apr 01, 2003 at 11:44:58PM +0900, Mattia Peronio wrote: > > >>I would like to give my contribution to the ruby community, publishing this simple program (my first ruby program!) which cleans Opera bookmarks from double entries. It works, but use it at your own risk. It also convinced me about the power of ruby. >> >> >However, in this case you could just do > > buff = File.open(filename, "r").read > > > The only problem with this is that the file does not get closed until the GC runs. I've found the following utility methods to be extremely useful for these kinds of file operations: class File # Reads the contents of the specified file_name and returns them as a String. def File.read(file_name) File.open(file_name) { |f| f.read } end # Writes +content+ to the file with the specified +file_name+, overwriting # any existing content of the file. def File.write(file_name, content) File.open(file_name, 'w') { |f| f.write(content) } end # Writes +content+ to the file with the specified +file_name+, appending to # any existing content of the file. def File.append(file_name, content) File.open(file_name, 'a') { |f| f.write(content) } end # Reads the contents of the file with the specified +file_name+ and passes # the contents to the provided block. The contents of the file are then # replaced by whatever is returned from the block. def File.filter(file_name) File.write(file_name, yield(File.read(file_name))) rescue LocalJumpError # i.e. no block was given # ignore, leaving the file unmodified end end -- Jason Voegele "We believe that we invent symbols. The truth is that they invent us." -- Gene Wolfe, The Book of the New Sun