Ruby Newbie homepage Ruby Newbie homepage

How to use

Quick guide

Official content
Returns a slice of bits from self.
With argument offset, returns the bit at the given offset, where offset 0 refers to the least significant bit:
n = 0b10 # => 2
n[0]     # => 0
n[1]     # => 1
n[2]     # => 0
n[3]     # => 0
In principle, n[i] is equivalent to (n >> i) & 1. Thus, negative index always returns zero:
255[-1] # => 0
With arguments offset and size, returns size bits from self, beginning at offset and including bits of greater significance:
n = 0b111000       # => 56
"%010b" % n[0, 10] # => "0000111000"
"%010b" % n[4, 10] # => "0000000011"
With argument range, returns range.size bits from self, beginning at range.begin and including bits of greater significance:
n = 0b111000      # => 56
"%010b" % n[0..9] # => "0000111000"
"%010b" % n[4..9] # => "0000000011"
Raises an exception if the slice cannot be constructed.
 
               static VALUE
int_aref(int const argc, VALUE * const argv, VALUE const num)
{
    rb_check_arity(argc, 1, 2);
    if (argc == 2) {
        return int_aref2(num, argv[0], argv[1]);
    }
    return int_aref1(num, argv[0]);

    return Qnil;
}
            

Was this page useful?