Converting an integer to a hexadecimal string in Ruby

Matt Haughton picture Matt Haughton · Sep 17, 2008 · Viewed 134.9k times · Source

Is there a built in way to convert an integer in Ruby into its hexadecimal equivalent?

Something like the opposite of String#to_i:

"0A".to_i(16) #=>10

Like perhaps:

"0A".hex #=>10

I know how to roll my own, but it's probably more efficient to use a built in Ruby function.

Answer

Jean picture Jean · Sep 17, 2008

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