Converting an integer to a hexadecimal string in Ruby Converting an integer to a hexadecimal string in Ruby ruby ruby

Converting an integer to a hexadecimal string in Ruby


You can give to_s a base other than 10:

10.to_s(16)  #=> "a"

Note that in ruby 2.4 FixNum and BigNum were unified in the Integer class. If you are using an older ruby check the documentation of FixNum#to_s and BigNum#to_s


How about using %/sprintf:

i = 20"%x" % i  #=> "14"


To summarize:

p 10.to_s(16) #=> "a"p "%x" % 10 #=> "a"p "%02X" % 10 #=> "0A"p sprintf("%02X", 10) #=> "0A"p "#%02X%02X%02X" % [255, 0, 10] #=> "#FF000A"