Last active
December 14, 2015 01:58
-
-
Save georgeu2000/5009767 to your computer and use it in GitHub Desktop.
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 RomanNumeral | |
def self.to_arabic roman_number | |
add_roman roman_number | |
end | |
private | |
def self.add_roman roman_number | |
result = 0 | |
( 0..roman_number.size - 2 ).each do |i| | |
this_char = roman_number[i] | |
next_char = roman_number[i+1] | |
next_is_greater( this_char, next_char ) ? | |
result -= roman_lookup( this_char ) : | |
result += roman_lookup( this_char ) | |
end | |
result += roman_lookup last_char_for( roman_number ) | |
end | |
def self.last_char_for str | |
str.split('').last | |
end | |
def self.next_is_greater first,second | |
to_arabic( second ) > to_arabic( first ) | |
end | |
def self.roman_lookup(character) | |
case character | |
when "I" | |
1 | |
when "V" | |
5 | |
when "X" | |
10 | |
when 'L' | |
50 | |
when "C" | |
100 | |
when 'D' | |
500 | |
when 'M' | |
1000 | |
end | |
end | |
end | |
describe RomanNumeral do | |
it "to arabic" do | |
RomanNumeral.to_arabic('MDL').should == 1550 | |
RomanNumeral.to_arabic('CCXCI').should == 291 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks Jim for an awesome Vital Testing workshop!