| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Name | Name | Last commit date | ||
|---|---|---|---|---|
A simple, pure-Ruby 'bit field' object.
Originally built to help power a bloom filter, although there are other higher level libraries for that task now (https://github.com/igrigorik/bloomfilter-rb is a popular one.)
BitArray has changed little over the years, but has been maintained to work within a typical, modern Ruby environment and works with Ruby 2.1+ through Ruby 3.x.
bundle add bitarrayTo use:
require 'bitarray'Create a bit array 1000 bits wide:
ba = BitArray.new(1000)Setting and reading bits:
ba[100] = 1
ba[100]
#=> 1
ba[100] = 0
ba[100]
#=> 0More:
ba = BitArray.new(20)
[1,3,5,9,11,13,15].each { |i| ba[i] = 1 }
ba.to_s
#=> "01010100010101010000"
ba.total_set
#=> 7Initializing BitArray with a custom field value:
ba = BitArray.new(16, ["0000111111110000"].pack('B*'))
ba.to_s # "1111000000001111"BitArray by default stores the bits in reverse order for each byte. If for example, you are initializing BitArray with Redis raw value manipulated with setbit / getbit operations, you will need to tell BitArray to not reverse the bits in each byte using the reverse_byte: false option:
ba = BitArray.new(16, ["0000111111110000"].pack('B*'), reverse_byte: false)
ba.to_s # "0000111111110000"Thanks to Michael Slade for encouraging me to update this library on its 10th birthday and for suggesting finally using String's getbyte and setbyte methods now that we're all on 1.9+ compatible implementations.
Further thanks to @tdeo, @JoshuaSP, @dalibor, @yegct and @m1lt0n for pull requests.
MIT licensed. Copyright 2007-2026 Peter Cooper.
| Back | FazBrowse Home | New Git URL |