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
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.
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
number unitpattern and perform the conversion yourself. Shouldn't be that hard. – Stefan Sep 10 '18 at 10:09