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.
str.hex
str
: This is the string whose leading numbers’ hexadecimal representation we want to get.
The value returned is a hexadecimal.
# 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
Lines 2-5: We create some string variables and initialize them.
Lines 8-11: We call the hex
method on the strings created and store the results on variables r1
, r2
, r3
, and r4
.
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.