Skip to content

Instantly share code, notes, and snippets.

@cho45
Created January 19, 2016 03:04
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 cho45/a88d860a3453ad2bcbf2 to your computer and use it in GitHub Desktop.
Save cho45/a88d860a3453ad2bcbf2 to your computer and use it in GitHub Desktop.
def sizeof(template)
x = Class.new(Numeric) do
def to_str; ""; end
def to_int; 0; end
# implicit to_f is called only with Numeric subclass
def to_f; 0.0; end
end.new
size = template.scan(/([a-zA-Z][_!]?[<>]?)([0-9]*)/).reduce(0) {|r,(_,n)|
r + (n.empty?? 1 : n.to_i)
}
# p [template, size]
Array.new(size) { x }.pack(template).size
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment