Skip to content

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

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.

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