From: Phrogz Date: 2007-06-07T05:00:13+09:00 Subject: Re: best DRY solution for this task On Jun 6, 11:57 am, anansi wrote: > I'm reading a file byte for byte. This file is structured and I try to > give out each structures element and the meaning of it. So let's pretend > the file content would be this in bytes (you get it e.g. with > file.read(7)): 1 3d 0 233 0 1 2f a) You might want to look into the BitStruct library. b) See the following. It's up to you how much work you want to put in the common 'eat' method, versus how much you want to leave up to the proc for each particular matcher. # Just for no-file testing require 'stringio' bytes = [ 1, 0x3d, 0, 233, 0, 1, 0x2f ] byte_string = StringIO.new( bytes.map{ |b| b.chr }.join ) class ByteEater def initialize( title, num_bytes, &block ) @title = title @num_bytes = num_bytes @proc = block end def eat( file ) bytes = file.read( @num_bytes ) print( "#@title: " ) @proc.call( bytes ) bytes.each_byte{ |x| print "%x" % x } puts "" end end structure = [ ByteEater.new( 'startflag', 3 ){ |bytes| if bytes == "\01\x3d\0" print " good" else print " bad" end }, ByteEater.new( 'dbg_mode', 1 ){ |bytes| case bytes when 1.chr print " on" when 255.chr print "don't know" else print "bad" end }, ] structure.each{ |eater| eater.eat( byte_string ) } #=> startflag: good13d0 #=> dbg_mode: bade9