rubyguides

String#oct

Overview

String#oct interprets the leading characters of a string as an octal (base-8) number and returns the corresponding integer. It is useful when you have a string representation of an octal number and need to work with its numeric value.

Unlike String#to_i, which defaults to base-10, oct reads the string as base-8. The method also supports binary (0b) and hexadecimal (0x) prefixes, and handles a leading minus sign for negative numbers.

Signature

str.oct -> integer

Takes no arguments. Returns an Integer.

Basic Examples

"10".oct   # => 8
"010".oct  # => 8
"100".oct  # => 64
"0".oct    # => 0

A leading 0 does not automatically trigger octal interpretation in Ruby — "010".to_i returns 10, not 8. oct exists precisely for this purpose.

Prefix Support

oct recognizes binary and hexadecimal prefixes:

"0b10".oct   # => 2   (binary)
"0x10".oct   # => 16  (hexadecimal)
"-010".oct   # => -8  (negative octal)

This cross-base behavior can be convenient but also surprising — see Gotchas below.

Stopping at Non-Octal Characters

Parsing stops at the first character that is not a valid octal digit (0–7):

"10xyz".oct   # => 8   (parses "10", stops at "xyz")
"1_0_1x".oct  # => 65  (Ruby 2.0+ ignores underscores in digit sequences)

Underscores in numeric strings are ignored, consistent with Ruby’s numeric literal syntax.

Invalid or Unrecognised Leading Characters

If the string is empty or begins with no valid octal digits, oct returns 0. This is because octal digits are limited to 0–7, so a leading character like a in "abc" simply doesn’t match any valid digit:

"".oct     # => 0
"abc".oct  # => 0

The Silent-Zero Gotcha

A string containing 8 or 9 returns 0, not an error:

"8".oct    # => 0
"9".oct    # => 0
"080".oct  # => 0   (0 is valid, but 8 is not — parsing stops and returns 0)

This silent failure is a common source of bugs. If you expect "080" to produce 64 (the octal interpretation), you will get 0 instead. Always validate input or use Integer() if you need stricter parsing.

Ruby Version Notes

Ruby 2.0+ ignores underscores in digit sequences (e.g., "1_0_1x".oct => 65).

See Also

  • String#hex — converts leading hex digits to an integer
  • Integer class — Ruby’s integer type and related conversion methods