Packing / unpacking UUIDs in Ruby

ruby, uuid

Solution

You can use `Array.pack` to pack your string:

First you need to turn it to array of 16-bit integers:

num_arr = "217aad3b-0b3d-4df0-a9ee-4fc9708f40bd".scan(/[0-9a-f]{4}/).map { |x| x.to_i(16) }
# => [8570, 44347, 2877, 19952, 43502, 20425, 28815, 16573]

Then pack it:

packed = num_arr.pack('n*')
# => "!z\xAD;\v=M\xF0\xA9\xEEO\xC9p\x8F@\xBD"
packed.bytesize
# => 16

`packed` is a string, but in Ruby byte arrays are represented as strings.

Problem

If I have a UUID string like the following: ``` 217aad3b-0b3d-4df0-a9ee-4fc9708f40bd ``` How do I pack that into a byte array (16 bytes) so that I can send it over HTTP as binary data? Given the byte array, what is the function that unpacks it into a string like the one above?

Original source