Skip to content

Instantly share code, notes, and snippets.

@dmshvetsov
Created December 28, 2020 07:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmshvetsov/493092ed5c525332248944e135119c03 to your computer and use it in GitHub Desktop.
Save dmshvetsov/493092ed5c525332248944e135119c03 to your computer and use it in GitHub Desktop.
Integer to Roman Number string conversion (kata, exercise)
class Roman
NUMS = [
[10, 'X'],
[9, 'IX'],
[5, 'V'],
[4, 'IV'],
[1, 'I']
].freeze
def self.from(val)
new(val.to_i)
end
def initialize(int)
@value = NUMS.reduce('') do |acc, (num, roman)|
while int >= num
acc += roman
int -= num
end
acc
end
end
def to_s
@value
end
end
RSpec.describe Roman do
it 'should convert 1 number to I' do
expect(Roman.from(1).to_s).to eq('I')
end
it 'should convert 2 number to II' do
expect(Roman.from(2).to_s).to eq('II')
end
it 'should convert 4 number to IV' do
expect(Roman.from(4).to_s).to eq('IV')
end
it 'should convert 7 number to VII' do
expect(Roman.from(7).to_s).to eq('VII')
end
it 'should convert 9 number to VII' do
expect(Roman.from(9).to_s).to eq('IX')
end
it 'should convert 10 number to X' do
expect(Roman.from(10).to_s).to eq('X')
end
it 'should convert 13 number to XIII' do
expect(Roman.from(13).to_s).to eq('XIII')
end
it 'should convert 26 number to XXVI' do
expect(Roman.from(26).to_s).to eq('XXVI')
end
it 'should convert 39 number to XXXIX' do
expect(Roman.from(39).to_s).to eq('XXXIX')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment