Skip to content
instance method

String#hex

() -> ::Integer
hex → integer

Interprets the leading substring of self as hexadecimal, possibly signed; returns its value as an integer.

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

  • One or more character 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:

    Example
    'f'.hex        # => 15
    '11'.hex       # => 17
    'FFF'.hex      # => 4095
    'fffg'.hex     # => 4095
    'foo'.hex      # => 15   # 'f' hexadecimal, 'oo' not.
    'bar'.hex      # => 186  # 'ba' hexadecimal, 'r' not.
    'deadbeef'.hex # => 3735928559
    
  • '0x' or '0X', followed by one or more hexadecimal digits:

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

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

Example
'-fff'.hex      # => -4095
'-0xFFF'.hex    # => -4095

For any substring not described above, returns zero:

Example
'xxx'.hex     # => 0
''.hex        # => 0

Note that, unlike oct, this method interprets only hexadecimal, and not binary, octal, or decimal notations:

Example
'0b111'.hex   # => 45329
'0o777'.hex   # => 0
'0d999'.hex   # => 55705

Related: See Converting to Non-String.

See also #hash #include? #gsub! #index also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0