From: "Anders Engström" Date: 2005-01-13T00:26:38+09:00 Subject: Re: Comparing two files for equality On Wed, Jan 12, 2005 at 09:11:17PM +0900, Florian Gross wrote: > Edgardo Hames wrote: > > >Hi everybody, > > Moin. > > >I tried to implement a program that > >compares two files for equality. I came up with the following trivial > >solution > > > >puts (IO.readlines file[0]) == (IO.readlines file[1]) > > > >Have you got any other suggestions? > > Not much different: > > def files_equal?(*files) > files.map do |file| > File.size file > end.uniq.size <= 1 and > files.map do |file| > File.read file > end.uniq.size <= 1 > end > > This ought to be slightly faster in the average case. > > Other optimizations would be reading the files line-wise in parallel and > bailing out as soon as one of the lines differs. > Another alternative - probably slow as h*ll, but... def files_equals?(*files) require 'digest/md5' return files.map do |file| Digest::MD5.hexdigest(File.read(file)) end.uniq.size == 1 end //Anders -- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Anders Engstr�m aengstrom@gnejs.net . http://www.gnejs.net PGP-Key: ED010E7F . [Your mind is like an umbrella. It doesn't work unless you open it.]