Converting numbers to hex using to_s in Ruby

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

Mac

Cocoon Development Training

We'd highly recommend Cocoon for Apple development and Apple training

Productivity

Adding issues from other organisations into Github Projects

Let's talk about how you can add issues from other organisations into your Github Project