Method: BitArray#initialize
- Defined in:
- ext/bitarray.c
#new(size) ⇒ Object #new(string) ⇒ Object #new(array) ⇒ Object
When called with a size, creates a new BitArray of the specified size, with all bits cleared. When called with a string or an array, creates a new BitArray from the argument.
If a string is given, it should consist of ones and zeroes. If there are any other characters in the string, the first invalid character and all following characters will be ignored.
b = BitArray.new("10101010") => 10101010
b = BitArray.new("1010abcd") => 1010
b = BitArray.new("abcd") =>
If an array is given, the BitArray is initialized from its elements using the following rules:
-
0, false, or nil => 0
-
anything else => 1
Note that the 0 is a number, not a string. “Anything else” means strings, symbols, non-zero numbers, subarrays, etc.
b = BitArray.new([0,0,0,1,1,0]) => 000110
b = BitArray.new([false, true, false]) => 010
b = BitArray.new([:a, :b, :c, [:d, :e]]) => 1111
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 |
# File 'ext/bitarray.c', line 289
static VALUE
rb_bitarray_initialize(VALUE self, VALUE arg)
{
if (TYPE(arg) == T_FIXNUM || TYPE(arg) == T_BIGNUM) {
struct bit_array *ba;
Data_Get_Struct(self, struct bit_array, ba);
long bits = NUM2LONG(arg);
if (bits <= 0) {
ba->bits = 0;
ba->array_size = 0;
return self;
}
ba->bits = bits;
ba->array_size = ((bits - 1) / UINT_BITS) + 1;
ba->array = ruby_xcalloc(ba->array_size, UINT_BYTES);
return self;
} else if (TYPE(arg) == T_STRING) {
return rb_bitarray_from_string(self, arg);
} else if (TYPE(arg) == T_ARRAY) {
return rb_bitarray_from_array(self, arg);
} else {
rb_raise(rb_eArgError, "must be size, string, or array");
}
}
|