From: "Simon Kröger" Date: 2007-10-04T23:35:03+09:00 Subject: Re: Human readable file sizes Jes�s Gabriel y Gal�n schrieb: > Hi, > > I have a list of files and I need to produce a string containing the > size of each file, but in human readable format. With that I mean > something like what df -h does: make an approximation to the nearest > unit (B, KB, MB, GB, etc). Is this already done somewhere? This is > what I have now: > > Find.find(folder) do |file| > match = regexp.match(File.basename(file)); > if match > size = File.stat(file).size > puts size # would like a human readable format > end > end > > Thanks, > > Jesus. Like this: ---------------------------------------------- class Numeric def to_human units = %w{B KB MB GB TB} e = (Math.log(self)/Math.log(1024)).floor s = "%.3f" % (to_f / 1024**e) s.sub(/\.?0*$/, units[e]) end end ---------------------------------------------- Note: this may be not 100% correct for very large values (like TB) because Math.log uses floating point arithmetic. cheers Simon