What is the String.hex method in Ruby?
Overview
In Ruby, the hex method applied to a string takes the string’s leading numbers and returns their hexadecimal representation. If zero is the leading number, then zero is returned.
Syntax
str.hex
Parameters
str: This is the string whose leading numbers’ hexadecimal representation we want to get.
Return value
The value returned is a hexadecimal.
Code example
# create some stringsstr1 = "1hello"str2 = "20hellos"str3 = "1234hellos"str4 = "0hello"# get hexadecimal valuesr1 = str1.hexr2 = str2.hexr3 = str3.hexr4 = str4.hex# print resultsputs r1puts r2puts r3puts r4
Explanation
-
Lines 2-5: We create some string variables and initialize them.
-
Lines 8-11: We call the
hexmethod on the strings created and store the results on variablesr1,r2,r3, andr4. -
Lines 14-17: We print the results to the console.
As we can see from the output of the code above, the leading numbers of the string are returned by the hex method as hexadecimals.