From: Michael Neumann Date: 2004-06-14T17:14:09+09:00 Subject: Re: [RCR]: Replace pack and unpack with OO versions On Mon, Jun 14, 2004 at 02:48:38PM +0900, Martin DeMello wrote: > Bill Atkins wrote: > > Rather than having code like this: > > > > flags, ignore, length, name = data.unpack "nnna*" > > > > let's try this: > > > > u = Unpacker.new data > > flags, ignore, length, name = u.word, u.word, u.word, u.string > > > > I think this looks a lot neater and is much more maintainable. A > > similar thing could be done with pack. > > Alternatively, something I've been thinking of is to let pack and unpack > take array arguments, which are 'compiled' into pack/unpack strings. > > e.g. flags, ignore, length, name = u.unpack [:word, :word, :word, > :string] > > All the compiler would have to do is translate symbols, and pass numbers > through unchanged. Or, if you wanted to construct it in terms of pairs > like [[:string, 3]], just run a flatten first. It would be nice if Packer/Unpacker would work on IO/File objects. I've written a BinaryReader and BinaryWriter mixin module, with methods like: read_word8(byte_order=ByteOrder::Native) read_word8_big ..._network read_word8_little read_word8_native and the same for word16, word32, int8, int16... int's are signed integers, word are unsigned. And to use it, you just have to extend your io object: require 'stringio' io = StringIO.new("Hello World") io.extend(BinaryReader) p io.read_word32 It's easy to add a unpack method: class BinaryReader def unpack(*spec) spec.map {|s| send("read_#{s}")} end end io.unpack(:word8, :word8, :word32_little) Regards, Michael