convert a number from base 10 to base 16 in ruby

To convert a number from base 10 to base 16 (hexadecimal) in Ruby, you can use the to_s method with a base of 16.

main.rb
decimal_num = 255
hex_num = decimal_num.to_s(16)
puts hex_num # outputs "ff"
77 chars
4 lines

In the example above, we first define a decimal number 255. We then call the to_s method on this number with a base of 16 to get the hexadecimal representation of the number. The resulting value is then stored in the hex_num variable.

Note that the resulting value is returned as a string, which is important to keep in mind when using the value in further calculations or comparisons.

gistlibby LogSnag