Skip to content

Instantly share code, notes, and snippets.

@samshull
Created November 9, 2012 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samshull/4046632 to your computer and use it in GitHub Desktop.
Save samshull/4046632 to your computer and use it in GitHub Desktop.
the metrics of numbers
module Metric
PREFIXES = {
:yotta => 8,
:zetta => 7,
:exa => 6,
:peta => 5,
:tera => 4,
:giga => 3,
:mega => 2,
:kilo => 1,
:hecto => 2/3,
:deca => 1/3,
:deci => -1/3,
:centi => -2/3,
:milli => -1,
:micro => -2,
:nano => -3,
:pico => -4,
:femto => -5,
:atto => -6,
:zepto => -7,
:yocto => -8,
}
PREFIXES.each do |key, exponent|
define_method(key) { self * 1_000**exponent }
end
end
module Bytes
PREFIXES = {
:yotta => [:Y, 8],
:zetta => [:Z, 7],
:exa => [:E, 6],
:peta => [:P, 5],
:tera => [:T, 4],
:giga => [:G, 3],
:mega => [:M, 2],
:kilo => [:K, 1],
}
PREFIXES.each do |key, (symbol, exponent)|
define_method(:"#{key}bits") { self * 1024**exponent }
alias_method :"#{symbol}b", :"#{key}bits"
alias_method :"#{key}bytes", :"#{key}bits"
alias_method :"#{symbol}B", :"#{key}bytes"
end
def bits
self * 8
end
end
class Fixnum
include Metric
include Bytes
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment