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

Freelancing

Getting the most out of your agency

Here are some tips based on years of working with, for, and as an agency on how to get the most out of any work you do.

VS Code Web Dev

Select multiple lines in VS Code

How to select multiple lines to edit at once within VS Code