On Wed, Apr 02, 2003 at 07:03:47AM +0900, Calum Shaw-Mackay wrote:
> I have a fixnum which is essentially a bit flag
> i.e.
> a=1,b=2,c=4,d=8 and so on
> I use binary & to work out if a particular flag is set and output a given
> message, unfortunatley this leads to lots of puts x if(value & CONST_A) ==
> CONST_A
> I pass in the messages in an array but the code looks very C-ish - is there
> any construct in ruby that will allow me to get around this long winded code
> without having a large array of boolean values

Fixnum already has bit references built-in as the [] operator:

  a = 35
  p a[0]  #>> 1  (bit 0)
  p a[1]  #>> 1  (bit 1)
  p a[2]  #>> 0  (bit 2)
  .. etc

However, '0' and '1' are both treated as true. You could always override it
to return 'false' and 'true' instead.

Or maybe you just want a wrapper method for your existing constants:

  class Fixnum
    def bit_set?(x)
      (self & x) != 0
    end
  end

  p 35.bit_set?(1)   # >>true
  p 35.bit_set?(2)   # >>true
  p 35.bit_set?(4)   # >>false

I notice there is a 'bitvector' class in RAA, haven't looked at it though.

Regards,

Brian.