Skip to content

Instantly share code, notes, and snippets.

@alisdair
Created June 7, 2011 10:45
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 alisdair/1012026 to your computer and use it in GitHub Desktop.
Save alisdair/1012026 to your computer and use it in GitHub Desktop.
String#unpack format string width
# http://www.ruby-doc.org/core/classes/String.html#M001112
#
# Calculate how many bytes String#unpack will read for a format string.
#
# Only guaranteed to work with the characters defined in classes, which are
# the sensible ones you should be using anyway. So there.
#
# Notably will not work with x, X, @, and so on.
def width(format)
classes = { "AazCc" => 1, "Ssn" => 2, "LlNVFfeg" => 4, "QqDdEG" => 8 }
bytes = Hash[classes.map {|k,v| k.each_char.map {|x| [x, v] } }.reduce(:+)]
directives = format.scan(/([A-Za-z])(\d*)/)
directives.map { |c,n| b = bytes[c] * [1, n.to_i].max }.reduce(:+)
end
p width("NnccNcc")
p width("N2s48")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment