From: William James Date: 2007-10-05T01:00:08+09:00 Subject: Re: Human readable file sizes On Oct 4, 5:05 am, "Jesús Gabriel y Galán" wrote: > 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. def kilo n count = 0 while n >= 1024 and count < 4 n /= 1024.0 count += 1 end format("%.2f",n) + %w(B KB MB GB TB)[count] end [1,1024,1_000_000,8_000_000,9_000_000_000, 3_000_000_000_000].each{|n| puts kilo(n) }