将人类可读的文件大小转换为 ruby 中的字节

Convert human readable file size to bytes in ruby

我经历了这个link。我的要求与此完全相反。例如,字符串 10KB 需要转换为 10240(其等效字节大小)。我们有任何 gem 吗?或 ruby 中的内置方法?我做了我的研究,我没能发现它

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 等,那么您只需添加乘数即可。

这是一个使用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