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 strings
str1 = "1hello"
str2 = "20hellos"
str3 = "1234hellos"
str4 = "0hello"
# get hexadecimal values
r1 = str1.hex
r2 = str2.hex
r3 = str3.hex
r4 = str4.hex
# print results
puts r1
puts r2
puts r3
puts r4

Explanation

  • 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.

Free Resources