# paulfioravanti's solution

## to Hexadecimal in the Ruby Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

Convert a hexadecimal number, represented as a string (e.g. "10af8c"), to its decimal equivalent using first principles (i.e. no, you may not use built-in or external libraries to accomplish the conversion).

On the web we use hexadecimal to represent colors, e.g. green: 008000, teal: 008080, navy: 000080).

The program should handle invalid hexadecimal strings.

For installation and learning resources, refer to the exercism help page.

For running the tests provided, you will need the Minitest gem. Open a terminal window and run the following command to install minitest:

``````gem install minitest
``````

If you would like color output, you can `require 'minitest/pride'` in the test file, or note the alternative instruction, below, for running the test file.

Run the tests from the exercise directory using the following command:

``````ruby hexadecimal_test.rb
``````

To include color from the command line:

``````ruby -r minitest/pride hexadecimal_test.rb
``````

## Source

All of Computer Science http://www.wolframalpha.com/examples/NumberBases.html

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

``````require 'minitest/autorun'

def test_hex_1_is_decimal_1
end

def test_hex_c_is_decimal_12
skip
end

def test_hex_10_is_decimal_16
skip
end

def test_hex_af_is_decimal_175
skip
end

def test_hex_100_is_decimal_256
skip
end

def test_hex_19ace_is_decimal_105166
skip
end

def test_invalid_hex_is_decimal_0
skip
end

def test_black
skip
end

def test_white
skip
end

def test_yellow
skip
end
end``````
``````# frozen_string_literal: true

HEX_DIGITS = "0123456789ABCDEF"
private_constant :HEX_DIGITS
HEX_STRING = /\A[#{HEX_DIGITS}]+\z/
private_constant :HEX_STRING
BASE = 16
private_constant :BASE

def initialize(string)
@string = string.upcase
end

def to_decimal
return 0 unless string.match?(HEX_STRING)
string.chars.reverse.each.with_index.sum(&method(:hex_to_dec))
end

private

def hex_to_dec((hex_character, exponent))
HEX_DIGITS.index(hex_character) * BASE**exponent
end
end``````