Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby String#unpack

Tags:

ruby

unpack

I have a packed string of 3 strings that is composed in a way so that I have an integer, specifying the byte length of the next item and then that item's bytes and then the next item's bytesize, etc. as if somebody did:

[a.bytesize, a, b.bytesize, b, c.bytesize, c].pack("na*na*na*")

How can I properly unpack that in a simple manner? The Perl solution to this problem was:

my($a, $b, $c) = unpack("(n/a*)3", $data)

For ruby, which apparently doesn't support '/' and parentheses in unpack, I'm using something like:

vals = []
3.times do
  size = data.unpack("n").first
  data.slice!(0, 2)
  vals << data.unpack("a#{size}").first
  data.slice!(0, size)
end

Is there an easier way to this?

like image 857
Speed Avatar asked Nov 12 '22 11:11

Speed


1 Answers

IMHO it is not as easy as in PERL, but this is some solution I can suggest.

unpacked = []
a, b, c = *unpacked << data.slice!(0, data.slice!(0, 2).unpack('S>').first) \
           until data.empty? 
like image 96
egghese Avatar answered Nov 15 '22 06:11

egghese