From: Chuck Remes Date: 2009-05-17T05:31:02+09:00 Subject: Re: BitStruct technique On May 14, 2009, at 4:53 PM, Joel VanderWerf wrote: > Chuck Remes wrote: >> >> In this example I passed in a hash as my message, but the +message+ >> variable could have been any object that could be interrogated to >> retrieve values for setting the bitstruct fields. I like this >> technique because it delegates the responsibility of proper >> bitstruct initialization to the class under construction. It nicely >> encapsulates that operation which I believe demonstrates the Single >> Responsibility principle. >> I hope this is of use to someone someday. >> cr > > I think I see where you're going with that, but just so others know, > the hash-based initialization is simple (though it does require that > the hash keys match the field names--and avoiding this is probably > the point of your code): > > require 'bit-struct' > > hsh = { :context => 1, :password => "foo", :usr_name => "bar" } > > class C < BitStruct > signed :context, 32, "c id" > char :password, 12*8, "pw" > char :usr_name, 12*8, "name" > end > > c = C.new hsh Joel, that's right. I probably shouldn't have used a hash as my example since you already have hash-based initialization built in. I meant for this to be a nice way to pass an arbitrary object to the constructor so the logic of getting data from that object would be encapsulated in one spot. I also could have built a temporary hash from the object argument and passed that to the superclass' constructor but I prefer the block-based initialization for readability. And thanks for creating such a neat library. I don't have a need for it now that I understand my problem domain better, but rest assured it is now a member of my toolbox for some future problem when I do need it. cr