Created
April 25, 2010 00:08
-
-
Save joelhelbling/378056 to your computer and use it in GitHub Desktop.
My implementation of the roman numerals kata (just the roman to arabic part).
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
# (Roman to Arabic only) | |
class RomanNumerals | |
def initialize | |
@numerals = { | |
"I" => 1, | |
"V" => 5, | |
"X" => 10, | |
"L" => 50, | |
"C" => 100, | |
:eol => 0 } | |
end | |
def convert(value) | |
sum = 0 | |
glyphs = value.split('').push(:eol) | |
previous_value = @numerals[glyphs.shift] | |
glyphs.each do |glyph| | |
this_value = @numerals[glyph] | |
if previous_value >= this_value then | |
sum += previous_value | |
previous_value = this_value | |
else | |
previous_value = this_value - previous_value | |
end | |
end | |
sum | |
end | |
end | |
describe RomanNumerals do | |
before :each do | |
@rn = RomanNumerals.new | |
end | |
it 'should have a convert method' do | |
@rn.should respond_to(:convert) | |
end | |
describe 'converting Roman to Arabic' do | |
it 'should, given "I", return 1' do | |
@rn.convert("I").should == 1 | |
end | |
it 'should, given "II", return 2' do | |
@rn.convert("II").should == 2 | |
end | |
it 'should, given "III", return 3' do | |
@rn.convert("III").should == 3 | |
end | |
it 'should, given "IV", return 4' do | |
@rn.convert("IV").should == 4 | |
end | |
it 'should, given "V", return 5' do | |
@rn.convert("V").should == 5 | |
end | |
it 'should, given "VI", return 6' do | |
@rn.convert("VI").should == 6 | |
end | |
it 'should, given "VII", return 7' do | |
@rn.convert("VII").should == 7 | |
end | |
it 'should, given "VIII", return 8' do | |
@rn.convert("VIII").should == 8 | |
end | |
it 'should, given "IX", return 9' do | |
@rn.convert("IX").should == 9 | |
end | |
it 'should convert X to 10' do | |
@rn.convert("X").should == 10 | |
end | |
it 'should convert XIV to 14' do | |
@rn.convert("XIV").should == 14 | |
end | |
it 'should convert XLII to 42' do | |
@rn.convert("XLII").should == 42 | |
end | |
it 'should convert XCIX to 99' do | |
@rn.convert("XCIX").should == 99 | |
end | |
it 'should convert CCCXCI to 391' do | |
@rn.convert("CCCXCI").should == 391 | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yeah, I started out with "it 'should return Y, given X" which is just all sorts of backwards. I went to the "given X, return Y" format because I wanted the test to describe a basic left-to-right "from -> to" sequence. In later tests I switched to "should convert X to Y" which I actually like better because it has the name of the method in it, and it leaves the "from" closer to the "to".