Created
August 30, 2013 00:56
-
-
Save broguinn/6385220 to your computer and use it in GitHub Desktop.
hexadecimal
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
| 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") |
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
| 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