Need help on #pack and #unpack

a = [‘2015’,“This is”, “one value”,“test”,‘9820’]
string = a.pack(‘ZAZZZ*’) # => “2015\x00This isone
value\x00test\x009820\x00”
string.unpack(‘ZZZZ’) # => [“2015”, “This isone value”, “test”,
“9820”]

But I want as

[“2015”, “This is one value”, “test”, “9820”]

How to do this ?

Add a space character to your inputs. AFAIK #pack and #unpack can’t do
that
for you. They’re not exactly string manipulation functions after all,
they’re data de/serialisers.

Matthew K. wrote in post #1139417:

Thank you very much. Could you tell me what do you mean by below ?
Probably one small use-case from your experience.

for you. They’re not exactly string manipulation functions after all,
they’re data de/serialisers.

Arup R. wrote in post #1139420:

Matthew K. wrote in post #1139417:

Thank you very much. Could you tell me what do you mean by below ?
Probably one small use-case from your experience.

for you. They’re not exactly string manipulation functions after all,
they’re data de/serialisers.

Well, for example, imagine you’re saving some image data as a TGA file.
You could do something like this:

COLOUR_MAP_NONE = 0
IMAGE_TYPE_RGB = 2

tga_header = [
0,
COLOUR_MAP_NONE,
IMAGE_TYPE_RGB,
0, 0, 32, # palette
0, 0, # x, y origin of pixels
255, 255, # width, height of image
24, # bits per pixel
0,
].pack ‘CCCSSCSSSSCC’

… and similarly, if you’re loading it:

identsz, cm_type, image_type,
cm_start, cm_length, cm_bits,
xstart, ystart, width, height, bits, descriptor =
tga_header.unpack ‘CCCSSCSSSSCC’

From my personal experience, I’ve mostly used pack/unpack for sending
data packets over a network (e.g. HTTP/2 is a binary format).

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs