Ruby中的漂亮文件大小? [英] Pretty file size in Ruby?

查看:140
本文介绍了Ruby中的漂亮文件大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个方法,将表示字节的整数转换为带有'prettied up'格式的字符串。

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

这是我的半工作尝试:

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 "#{s / self}#{e}" if self < s }
  end
end

我做错了什么?

推荐答案

Filesize gem怎么样?它似乎能够从字节(和其他格式)转换为漂亮的打印值:

How about the Filesize gem ? It seems to be able to convert from bytes (and other formats) into pretty printed values:

示例:

Filesize.from("12502343 B").pretty      # => "11.92 MiB"

http://rubygems.org/gems/filesize

这篇关于Ruby中的漂亮文件大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆