Last active
March 13, 2016 04:02
-
-
Save holdenhinkle/d9a57b6958819455cad8 to your computer and use it in GitHub Desktop.
Convert Hex to Decimal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Hex | |
HEX = { '1' => 1, '2' => 2, '3' => 3, | |
'4' => 4, '5' => 5, '6' => 6, | |
'7' => 7, '8' => 8, '9' => 9, | |
'a' => 10, 'b' => 11, 'c' => 12, | |
'd' => 13, 'e' => 14, 'f' => 15 } | |
attr_reader :string | |
def initialize(input) | |
@string = input.downcase | |
end | |
def to_decimal | |
return 0 if string.match(/[^0-9a-f]/) | |
string.split('').reverse | |
.each_with_index.map { |character, index| HEX[character] * 16 ** index } | |
.inject(&:+) | |
end | |
end | |
result = Hex.new('abcde2342').to_decimal | |
puts result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice. Is there a preference between
split('')
andchars
?