Search code examples
rubybytefilesize

Convert human readable file size to bytes in ruby


I went through this link. My requirement is the exact reverse of this. Example a string 10KB needs to be converted to 10240 (its equivalent byte size). Do we have any gem for this? or inbuilt method in ruby? I did my research, I wasn't able to spot it


Solution

  • There's filesize (rubygems)

    It's quite trivial to write your own:

    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
    

    If you need KiB, MiB etc then you just add multipliers.