Hexadecimal number validation with regex (Ruby)

Sometimes, we might want to know whether a given input is a hexadecimal number.

However, since there seems to be no pre-defined method designed for this purpose, I decided to implement one using Ruby.

(Inspired by a book entitled INTRODUCTION TO REGULAR EXPRESSIONS written by the Launch School team)

def hex?(num)
hex = true
num.chars.each do |digit|
hex = false unless digit.match(/[0-9A-Fa-f]/)
end
hex
end

Instead of the above regex that consists of 3 different ranges of alphanumeric characters, we can also use another regex I found while stackoverflowing:

\h

This simply breaks down the “num” into its digits by String#chars method and checks if each digit is a hexadecimal number. If that’s not the case, we set the “hex” local variable, which we initialized to “true” on line 2, to “false”. The method finally returns the “hex”, which will be either “true” or “false”.


Now, we are assuming that “num” is of a type String. Therefore the following code throws a “NoMethodError” even though 11 is a hexadecimal number, which will be 17 in decimal:

hex?(11)

This is because there is no “chars” method defined for 11, which is an object of Fixnum class. We could add a guard clause here such as:

num = num.to_s unless num.class == String

to ensure that we can call “String#chars” method on “num”.


We can test out the code:

hex1 = ‘17a5b4506e’
hex2 = ‘CDB50A4F59’
non_hex1 = ‘17a5bWWW4506e’
non_hex2 = ‘non hex :)’
hex?(hex1) #=> true
hex?(hex2) #=> true
hex?(non_hex1) #=> false
hex?(non_hex2) #=> false

Any feedback will be greatly appreciated (particularly any potential edge cases I may have omitted).