Converting numbers to hex using to_s in Ruby

How you can use the Ruby to_s method to convert numbers to hex

Today I learned that you can easily convert a number to its hex value by calling to_s on it along with the base you want to convert as a parameter on to_s.

170.to_s(16)
 => "aa"

Of course this means you can also convert it to binary (base 2)

170.to_s(2)
 => "10101010"

Personally I like my hexadecimals to be in uppercase, I could call to_s(16).upcase each time but that feels a little wasteful, why don’t we make a method to do that for us?

class Numeric
   def to_hex
      to_s(16).upcase
   end
end

My use case for this was to convert RGB values to Hex values, now generally when you do that you would want an RGB value of 0,0,0 to be converted into 000000, but as you can will calling to_hex on 0 currently produces 0.

0.to_hex
 => "0"

How do we change this? The method I went for was to pad my output after changing it to a string.

0.to_hex.rjust(2, '0')
 => "00"

Recent posts View all

SEO

Google follows URLs in text

Today I learned that Google follows URLs even when they are plain text

Web Dev

Check in with your database

It pays to take a step back and look at how your database is set up every so often. You will often find quick wins and hidden tech debt.