From: Robert Klemme Date: 2005-07-06T18:05:46+09:00 Subject: Re: Reading arbitrary data into a c-like structure Michael Neumann wrote: > Graham Nicholls wrote: >> I mentioned before that I'm writing a tool to extract data from a >> (dataease) database file according to a schema. In 'C' I'd do >> something like >> >> struct data >> { >> char header 4; >> int recno; >> char name[30]; >> char add_1[30]; >> ... >> unsigned int cr_limit ; >> } data; >> >> and if I set the compiler options right so the structure was closely >> packed, I could simply read the file into this structure, and print >> out the results using > > You need to read sizeof(data) bytes as a String, then unpack it. > > Simple example: > > C: > > struct data { > long a; > long b; > }; > > Ruby: > > str = handle.read(8) > a, b = str.unpack('LL') > > Regards, > > Michael Plus, if you want to do further processing, you can use any of Hash, Struct or OpenStruct for storage. If you create a struct for your special case you mighe even implement conversion methods: # untested Foo = Struct.new(:a, :b) class Foo def to_binary() [a,b].pack('LL') end def self.from_io(io) new *io.read(8).unpack('LL') end end Kind regards robert