Pretty file size in Ruby?

后端 未结 7 1853
半阙折子戏
半阙折子戏 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:27

    I agree with @David that it's probably best to use an existing solution, but to answer your question about what you're doing wrong:

    1. The primary error is dividing s by self rather than the other way around.
    2. You really want to divide by the previous s, so divide s by 1024.
    3. Doing integer arithmetic will give you confusing results, so convert to float.
    4. Perhaps round the answer.

    So:

    class Integer
      def to_filesize
        {
          'B'  => 1024,
          'KB' => 1024 * 1024,
          'MB' => 1024 * 1024 * 1024,
          'GB' => 1024 * 1024 * 1024 * 1024,
          'TB' => 1024 * 1024 * 1024 * 1024 * 1024
        }.each_pair { |e, s| return "#{(self.to_f / (s / 1024)).round(2)}#{e}" if self < s }
      end
    end
    

    lets you:

    1.to_filesize
    # => "1.0B"
    1020.to_filesize
    # => "1020.0B" 
    1024.to_filesize
    # => "1.0KB" 
    1048576.to_filesize
    # => "1.0MB"
    

    Again, I don't recommend actually doing that, but it seems worth correcting the bugs.

提交回复
热议问题