On Tue, May 06, 2003 at 06:10:40AM +0900, Daniel Carrera wrote:
> Could you explain to me how to use Array#pack?  PickAxe doesn't contain 
> almost anything:
> 
> Pickaxe:
>    a = [ "a", "b", "c" ]
>    n = [ 65, 66, 67 ]
>    a.pack("A3A3A3")"   # -> "a  b  c"
>    a.pack("a3a3a3")    # -> "a\000\000b\000\000c\000\000"
>    n.pack("ccc")       # -> "ABC"
> 
> 
> Where can I learn how to use Array#pack?

It's in the Pickaxe, you just have to look a bit...

http://www.rubycentral.com/book/ref_c_array.html

search for "Template characters for Array#pack" which is a table of the
different packing codes. In the HTML it sits just after the definition of
'include?', which is inconveniently not next to 'pack'...

The counterpart is String#unpack:
http://www.rubycentral.com/book/ref_c_string.html#String.unpack
(and its table of template characters is more sensibly placed :-)

But if you just want to pick individual bits out of a binary String you
don't need either:

   a = "hello"
   a[0]         #  104  (= 0x68 = ASCII code for 'h')
   a[1]         #  101  (= 0x65 = ASCII code for 'e')
   a[1][0]      #  1    (bit 0 of 0x65)
   a[1][1]      #  0    (bit 1 of 0x65)
   a[1][2]      #  1    (bit 2 of 0x65)
   # etc

i.e. String#[] extracts one byte as a Fixnum, and Fixnum#[] extracts one
bit as 0 or 1

Regards,

Brian.