Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Integer#[]

int[n] → 0, 1
int[n, m] → num
int[range] → num

Bit Reference—Returns the nth bit in the binary representation of int, where int[0] is the least significant bit.

Example
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:

Example
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 if n & ((1 << (j + 1)) - 1) is zero. Otherwise, raises an ArgumentError.

  • n[...j] is zero if n & ((1 << j) - 1) is zero. Otherwise, raises an ArgumentError.

Note that range operation may exhaust memory. For example, -1[0, 1000000000000] will raise NoMemoryError.

See also #>> #^ #>= #| also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1