Skip to content

Instantly share code, notes, and snippets.

@lkfken
Created June 21, 2012 19:25
Show Gist options
  • Save lkfken/2967945 to your computer and use it in GitHub Desktop.
Save lkfken/2967945 to your computer and use it in GitHub Desktop.
Verify the unpack string
require 'terminal-table'
def unpack_str_table(unpack_str, data = nil)
len = unpack_str.scan(/\d+/)
sum = 0; idx = 1
fields = len.map { |x| sum += x.to_i }
headings = %w( Index Length Start End )
headings << "Data" unless data.nil?
table = Terminal::Table.new :headings => headings
fields.each do |stop|
length = len[idx - 1].to_i
start = stop + 1 - length
row = [idx, length, start, stop]
row << data[idx - 1] unless data.nil?
table << row
idx += 1
end
table
end
line = '123abc456def'
unpack_str = 'A3A3A3A3'
fields_data = line.unpack(unpack_str)
puts unpack_str_table(unpack_str, fields_data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment