Pretty file size in Ruby?

后端 未结 7 1882
半阙折子戏
半阙折子戏 2020-12-13 20:06

I\'m trying to make a method that converts an integer that represents bytes to a string with a \'prettied up\' format.

Here\'s my half-working attempt:



        
7条回答
  •  别那么骄傲
    2020-12-13 20:25

    You get points for adding a method to Integer, but this seems more File specific, so I would suggest monkeying around with File, say by adding a method to File called .prettysize().

    But here is an alternative solution that uses iteration, and avoids printing single bytes as float :-)

    def format_mb(size)
      conv = [ 'b', 'kb', 'mb', 'gb', 'tb', 'pb', 'eb' ];
      scale = 1024;
    
      ndx=1
      if( size < 2*(scale**ndx)  ) then
        return "#{(size)} #{conv[ndx-1]}"
      end
      size=size.to_f
      [2,3,4,5,6,7].each do |ndx|
        if( size < 2*(scale**ndx)  ) then
          return "#{'%.3f' % (size/(scale**(ndx-1)))} #{conv[ndx-1]}"
        end
      end
      ndx=7
      return "#{'%.3f' % (size/(scale**(ndx-1)))} #{conv[ndx-1]}"
    end
    

提交回复
热议问题