0

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

3
  • Which units do you have to convert? – Stefan Sep 10 '18 at 10:03
  • Commonly used units of filesize, B, KB, MB, GB – user3636388 Sep 10 '18 at 10:05
  • 1
    I don't know any gem for this but you can probably parse a number unit pattern and perform the conversion yourself. Shouldn't be that hard. – Stefan Sep 10 '18 at 10:09
4

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.

-1

Here is a method using 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.