On Wed, 21 Mar 2001, Mathieu Bouchard wrote: > On Thu, 22 Mar 2001, Hugh Sasse Staff Elec Eng wrote: > > I've run up against something I thought I knew how to solve, but... [my code trimmed] > > > OK, horribly inefficient, but still. I have extended IO. Now, how > > do I get IO to initialize @c and @bitcount properly? > > I'd recommend against doing such tricks of renaming methods. I'd keep Yes, it is rather uncomfortable. (But your comment suggests it would have worked, which is worth knowing.) > that for cases where there is no other solution. > > class IO > def outputbit(bit) > @c ||= 0 > @bitcount ||= 0 Ah, yes, I remember seeing this done with hashes -- it seems to be the ruby idiom for "initialize unless initialised already". Mabye a good thing to go in the Wiki? > @c = (@c << 1) | bit > @bitcount += 1 > if @bitcount == 8 then > putc(@c) > @c = 0 > @bitcount = 0 > end > end > end > > or > > class IO > def outputbit(bit) > @c = ((@c||1) << 1) | bit > if @c[8]==1 then This took me a while to understand, but it is quite cunning. So bits 0...7 hold the data I will output and the 8th bit acts as a full flag. Nice. > putc(@c) > @c = 1 > end > end > end > > matju > > Thank you, Hugh