Difference between revisions of "Talk:Ruby bitfield"
Jump to navigation
Jump to search
(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…') |
m |
||
Line 2: | Line 2: | ||
Using actual bit operations on an Integer seems more straightforward... I'll see about setting up some timing tests to compare speed. | 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 | Here's a fairly clean conversion of your class (with minor modifications). | ||
Note that <tt>clear_all()</tt> and <tt>set_all</tt> are practically instantaneous. :) | Note that <tt>clear_all()</tt> and <tt>set_all</tt> are practically instantaneous. :) | ||
Revision as of 23:43, 9 April 2010
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 clean 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