Skip to content
instance method

String#oct

() -> ::Integer
oct → integer

Interprets the leading substring of self as octal, binary, decimal, or hexadecimal, possibly signed; returns their value as an integer.

In brief:

Example
# Interpreted as octal.
'777'.oct   # => 511
'777x'.oct  # => 511
'0777'.oct  # => 511
'0o777'.oct # => 511
'-777'.oct  # => -511
# Not interpreted as octal.
'0b111'.oct # => 7     # Interpreted as binary.
'0d999'.oct # => 999   # Interpreted as decimal.
'0xfff'.oct # => 4095  # Interpreted as hexadecimal.

The leading substring is interpreted as octal when it begins with:

  • One or more character representing octal digits (each in the range '0'..'7'); the string to be interpreted ends at the first character that does not represent an octal digit:

    '7'.oct      @ => 7
    '11'.oct     # => 9
    '777'.oct    # => 511
    '0777'.oct   # => 511
    '7778'.oct   # => 511
    '777x'.oct   # => 511
  • '0o', followed by one or more octal digits:

    Example
    '0o777'.oct  # => 511
    '0o7778'.oct # => 511
    

The leading substring is not interpreted as octal when it begins with:

  • '0b', followed by one or more characters representing binary digits (each in the range '0'..'1'); the string to be interpreted ends at the first character that does not represent a binary digit. the string is interpreted as binary digits (base 2):

    Example
    '0b111'.oct  # => 7
    '0b1112'.oct # => 7
    
  • '0d', followed by one or more characters representing decimal digits (each in the range '0'..'9'); the string to be interpreted ends at the first character that does not represent a decimal digit. the string is interpreted as decimal digits (base 10):

    Example
    '0d999'.oct  # => 999
    '0d999x'.oct # => 999
    
  • '0x', followed by one or more characters representing hexadecimal digits (each in one of the ranges '0'..'9', 'a'..'f', or 'A'..'F'); the string to be interpreted ends at the first character that does not represent a hexadecimal digit. the string is interpreted as hexadecimal digits (base 16):

    Example
    '0xfff'.oct  # => 4095
    '0xfffg'.oct # => 4095
    

Any of the above may prefixed with '-', which negates the interpreted value:

Example
'-777'.oct   # => -511
'-0777'.oct  # => -511
'-0b111'.oct # => -7
'-0xfff'.oct # => -4095

For any substring not described above, returns zero:

Example
'foo'.oct      # => 0
''.oct         # => 0

Related: see Converting to Non-String.

See also #next! #ord #next #partition also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0