Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
Integer#[]
(::int) -> ::Integer
(::int i, ::int len) -> ::Integer
(::Range[::int]) -> ::Integer
self[offset] → 0 or 1
self[offset, size] → integer
self[range] → integer
numeric.c
View on GitHub ↗
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;
}
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:
Example
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:
Example
255[-1] # => 0
With arguments offset and size, returns size bits from self, beginning at offset and including bits of greater significance:
Example
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:
Example
n = 0b111000 # => 56 "%010b" % n[0..9] # => "0000111000" "%010b" % n[4..9] # => "0000000011"
Raises an exception if the slice cannot be constructed.