Skip to content

Instantly share code, notes, and snippets.

@holdenhinkle
Last active March 13, 2016 04:02
Show Gist options
  • Save holdenhinkle/d9a57b6958819455cad8 to your computer and use it in GitHub Desktop.
Save holdenhinkle/d9a57b6958819455cad8 to your computer and use it in GitHub Desktop.
Convert Hex to Decimal
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
@hafbau
Copy link

hafbau commented Mar 13, 2016

Nice. Is there a preference between split('') and chars?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment