End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
Integer#[]
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;
}
Bit Reference—Returns the nth bit in the binary representation of int, where int[0] is the least significant bit.
a = 0b11001100101010 30.downto(0) {|n| print a[n] } #=> 0000000000000000011001100101010 a = 9**15 50.downto(0) {|n| print a[n] } #=> 000101110110100000111000011110010100111100010111001
In principle, n[i] is equivalent to (n >> i) & 1. Thus, any negative index always returns zero:
p 255[-1] #=> 0
Range operations n[i, len] and n[i..j] are naturally extended.
-
n[i, len]equals to(n >> i) & ((1 << len) - 1). -
n[i..j]equals to(n >> i) & ((1 << (j - i + 1)) - 1). -
n[i...j]equals to(n >> i) & ((1 << (j - i)) - 1). -
n[i..]equals to(n >> i). -
n[..j]is zero ifn & ((1 << (j + 1)) - 1)is zero. Otherwise, raises anArgumentError. -
n[...j]is zero ifn & ((1 << j) - 1)is zero. Otherwise, raises anArgumentError.
Note that range operation may exhaust memory. For example, -1[0, 1000000000000] will raise NoMemoryError.