Skip to content

Instantly share code, notes, and snippets.

@broguinn
Created August 30, 2013 00:56
Show Gist options
  • Select an option

  • Save broguinn/6385220 to your computer and use it in GitHub Desktop.

Select an option

Save broguinn/6385220 to your computer and use it in GitHub Desktop.
hexadecimal
def hexadecimal(hex_number)
hex = 0
letters = { "a" => 10, "b" => 11, "c" => 12, "d" => 13, "e" => 14, "f" => 15}
hex_number = hex_number.split("").map do |digit|
if letters.keys.include?(digit)
letters[digit]
else
digit
end
end
hex_number.reverse.each_with_index do |digit, index|
hex += digit.to_i * 16 ** index
end
hex
end
puts hexadecimal("-1b3a")
require 'rspec'
require 'hexadecimal'
describe 'hexadecimal' do
it 'translates digits' do
hexadecimal('0').should eq 0
hexadecimal('2').should eq 2
end
it 'translates a-f' do
hexadecimal('a').should eq 10
end
it 'raises an exception for negative values' do
expect {hexadecimal('-1b3a')}.to raise_exception
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment