hexadecimal.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Convert hexadecimal string to integer value
class Hexadecimal
  HEX_VALUES = [*'0'..'9', *'a'..'f'].zip(0..15).to_h

  def initialize(number)
    @number = number
  end

  def to_decimal
    return 0 unless /^[0-9a-f]+$/ =~ @number

    # Shift the accumulated value along one place and add this digit
    @number.chars.map { |c| HEX_VALUES[c] }.inject(0) { |a, e| a * 16 + e }
  end
end

Comments


You're not logged in right now. Please login via GitHub to comment