Skip to content

Instantly share code, notes, and snippets.

@a-chernykh
Created July 2, 2014 10:25
Show Gist options
  • Save a-chernykh/7cbf2209539571ad75c3 to your computer and use it in GitHub Desktop.
Save a-chernykh/7cbf2209539571ad75c3 to your computer and use it in GitHub Desktop.
class RomanToInt
def initialize(roman)
@roman = roman.downcase
end
def to_int
result = 0
roman = @roman
exceptions.each do |exception, exception_value|
count = roman.scan(exception).length
result += exception_value * count
roman.gsub! exception, ''
end
roman.chars.each do |roman_char|
result += values[roman_char]
end
result
end
private
def exceptions
{ 'iv' => 4,
'ix' => 9,
'xl' => 40,
'xc' => 90,
'cd' => 400,
'cm' => 900 }
end
def values
{ 'i' => 1,
'v' => 5,
'x' => 10,
'l' => 50,
'c' => 100,
'd' => 500,
'm' => 1_000 }
end
end
describe RomanToInt do
describe '#to_int' do
subject { described_class.new(roman).to_int }
describe 'I' do
let(:roman) { 'I' }
it { should eq 1 }
end
describe 'II' do
let(:roman) { 'II' }
it { should eq 2 }
end
describe 'III' do
let(:roman) { 'III' }
it { should eq 3 }
end
describe 'IV' do
let(:roman) { 'IV' }
it { should eq 4 }
end
describe 'V' do
let(:roman) { 'V' }
it { should eq 5 }
end
describe 'VI' do
let(:roman) { 'VI' }
it { should eq 6 }
end
describe 'VII' do
let(:roman) { 'VII' }
it { should eq 7 }
end
describe 'VIII' do
let(:roman) { 'VIII' }
it { should eq 8 }
end
describe 'IX' do
let(:roman) { 'IX' }
it { should eq 9 }
end
describe 'X' do
let(:roman) { 'X' }
it { should eq 10 }
end
describe 'XI' do
let(:roman) { 'XI' }
it { should eq 11 }
end
describe 'MCMIV' do
let(:roman) { 'MCMIV' }
it { should eq 1904 }
end
describe 'MCMLIV' do
let(:roman) { 'MCMLIV' }
it { should eq 1954 }
end
describe 'MCMXC' do
let(:roman) { 'MCMXC' }
it { should eq 1990 }
end
describe 'MMXIV' do
let(:roman) { 'MMXIV' }
it { should eq 2014 }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment