Let's make: Nintendo block to Megabyte/Gigabyte converter

It's just a matter of knowing the numbers.


· 1 min read

To make a block converter, we need to know what the conversions are:

MB GB Blocks
MB 1 1/1024 = 0.0009765625 8
GB 1024 1 8192
Blocks 1/8 = 0.125 1/8192 = 0.0001220703125 1
The value is the number of the size on top needed to get the size on the left

Then, we can start defining functions:

def bl_to_mb(bl) # block to mb
  return bl / 8

def bl_to_gb(bl) # block to gb
  return bl_to_mb(bl) / 1024 # nesting

def mb_to_bl(mb)
  return mb * 8

def gb_to_bl(gb)
  return gb * 8192

# we’ll include mb -> gb and viceversa for the sake of completion
def mb_to_gb(mb)
  return mb / 1024

def gb_to_mb(gb)
  return gb * 1024

We can wrap them up in a module, like so:

module Blockconverter
  # functions

And use it like so:

puts Blockconverter::gb_to_bl(4).to_s + " blocks" # => "32768 blocks"

We could wrap the returned integer in an interpolated string, like:

puts "#{Blockconverter::gb_to_bl(4)} blocks" # => "32768 blocks"

Of course there’s no advantage in taking either way, so feel free to choose the one that best suits you.

Let me know in the comments how you used this code and/or how you updated it!

You might also enjoy