Talk:Ruby bitfield
Revision as of 23:43, 9 April 2010 by Yobgod Ababua (talk | contribs) (Created page with 'It's a nice example, but why wouldn't you just use an Integer (an actual bitfield) rather than an Array or String? Using actual bit operations on an Integer seems more straightfo…')
It's a nice example, but why wouldn't you just use an Integer (an actual bitfield) rather than an Array or String? Using actual bit operations on an Integer seems more straightforward... I'll see about setting up some timing tests to compare speed.
Here's a fairly straightforward conversion of your class (with minor modifications). Note that clear_all() and set_all are practically instantaneous. :)
class BitField include Enumerable attr_reader :size def initialize(size) @size = size @field = 0 end def []=(position,value) value == 0 ? @field ^= 1 << position : @field |= 1 << position end def set(position) self[position] = 1 end def clear(position) self[position] = 0 end def [](position) @field[position] end def is_set?(position) @field[position] == 1 end def each(&block) @size.times { |position| yield @field[position] } end def are_set @result = Array.new @size.times { |position| self.is_set?(position) and @result << position } return @result end def to_s string = "" @size.times { |position| string += @field[position].to_s } return string end def clear_all @field = 0 end def set_all @field = (2 ** (@size+1)) -1 end end