String#hex
Signature
str.hex → Integer
No parameters. Parses the leading hexadecimal digit sequence from str and returns it as an Integer.
What It Does
String#hex scans the string from left to right for a sequence of hexadecimal characters (0–9, a–f, A–F). It accepts an optional sign (+ or -) at the start and an optional 0x prefix (case-insensitive). Parsing stops at the first non-hex character. The rest of the string is ignored.
This makes it useful for reading hex values from configuration files, parsing hex color codes, and interpreting hex-encoded data from hardware registers or network packets.
Return Values
| Condition | Return value |
|---|---|
| Leading hex digits found | Integer (base 16) |
| No leading hex digits | 0 |
| Empty string | 0 |
With 0x/0X prefix | Integer (prefix is ignored) |
With sign (+/-) | Signed integer |
Examples
Basic conversion
"ff".hex # => 255
"0xff".hex # => 255
"-0xff".hex # => -255
"aB".hex # => 171
"0xDEAD".hex # => 57005
The 0x prefix is optional. Both "ff" and "0xff" produce the same result.
Parsing stops at non-hex characters
"10xyz".hex # => 16
"0xFFG".hex # => 255
The moment a character that isn’t a valid hex digit appears, parsing stops. The G in "0xFFG" is simply ignored.
Hex Color to RGB
A common use case is extracting RGB channels from a hex color code:
def hex_to_rgb(hex_str)
hex_str.delete('#').hex
end
hex_to_rgb("#ff5733") # => 16735475
Extract individual channels by bit-shifting:
def hex_to_channels(hex_str)
hex = hex_str.delete('#').hex
r = (hex >> 16) & 0xff
g = (hex >> 8) & 0xff
b = hex & 0xff
[r, g, b]
end
hex_to_channels("#ff5733") # => [255, 87, 51]
String#hex vs Integer()
Unlike Integer(), String#hex never raises an exception — if no leading hex is found, it silently returns 0:
Integer("0x10") # => 16
"0x10".hex # => 16
Integer("xyz") # => ArgumentError
"xyz".hex # => 0
Use Integer() when you want strict parsing and an exception on bad input. Use String#hex when you want to silently skip over non-numeric strings.
See Also
- String#to_i — parse a string as an integer in a specific base (decimal by default)
- String#delete — remove characters like
#from a string before callinghex - String#unpack — decode binary data with template formats, including hex decoding via the
H*directive