【问题标题】:Convert human readable file size to bytes in ruby将人类可读的文件大小转换为 ruby​​ 中的字节
【发布时间】:2018-09-10 09:55:48
【问题描述】:

我经历了这个link。我的要求与此完全相反。示例 10KB 的字符串需要转换为 10240(其等效字节大小)。我们有这方面的宝石吗?还是红宝石中的内置方法?我做了研究,我无法发现它

【问题讨论】:

  • 你需要转换哪些单位?
  • 常用的文件大小单位,B,KB,MB,GB
  • 我对此一无所知,但您可能可以解析number unit 模式并自己执行转换。应该没那么难。

标签: ruby byte filesize


【解决方案1】:

filesize (rubygems)

自己写很简单:

module ToBytes
  def to_bytes
    md = match(/^(?<num>\d+)\s?(?<unit>\w+)?$/)
    md[:num].to_i * 
      case md[:unit]
      when 'KB'
        1024
      when 'MB'
        1024**2
      when 'GB'
        1024**3
      when 'TB'
        1024**4
      when 'PB'
        1024**5
      when 'EB'
        1024**6
      when 'ZB'
        1024**7
      when 'YB'
        1024**8
      else
        1
      end
  end
end

size_string = "10KB"
size_string.extend(ToBytes).to_bytes
=> 10240

String.include(ToBytes)
"1024 KB".to_bytes
=> 1048576

如果您需要KiBMiB 等,则只需添加乘数。

【讨论】:

    【解决方案2】:

    这是一个使用while的方法:

    def number_format(n)
       n2, n3 = n, 0
       while n2 >= 1e3
          n2 /= 1e3
          n3 += 1
       end
       return '%.3f' % n2 + ['', ' k', ' M', ' G'][n3]
    end
    
    s = number_format(9012345678)
    puts s == '9.012 G'
    

    https://ruby-doc.org/core/doc/syntax/control_expressions_rdoc.html#label-while+Loop

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-12
      • 1970-01-01
      • 2017-08-09
      • 1970-01-01
      • 1970-01-01
      • 2011-04-15
      • 2014-12-24
      相关资源
      最近更新 更多