String#oct
static VALUE
rb_str_oct(VALUE str)
{
return rb_str_to_inum(str, -8, FALSE);
}
Interprets the leading substring of self as octal, binary, decimal, or hexadecimal, possibly signed; returns their value as an integer.
In brief:
# 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:
'-777'.oct # => -511 '-0777'.oct # => -511 '-0b111'.oct # => -7 '-0xfff'.oct # => -4095
For any substring not described above, returns zero:
'foo'.oct # => 0 ''.oct # => 0
Related: see Converting to Non-String.