Skip to content

Instantly share code, notes, and snippets.

@zastrow
Last active December 11, 2015 01:59
Show Gist options
  • Save zastrow/4527099 to your computer and use it in GitHub Desktop.
Save zastrow/4527099 to your computer and use it in GitHub Desktop.
Final Exercise from "Learning to Program" Chapter 9. This program changes inserted numbers to the Roman Numeral equivalent in two different styles.
## Old Roman Style
def old_roman num
m = ( num ) / 1000
d = ( num % 1000 ) / 500
c = ( num % 500 ) / 100
l = ( num % 100 ) / 50
x = ( num % 50 ) / 10
v = ( num % 10 ) / 5
i = ( num % 5 )
puts 'Old Roman Stlye: ' +
( 'M' * m ) +
( 'D' * d ) +
( 'C' * c ) +
( 'L' * l ) +
( 'X' * x ) +
( 'V' * v ) +
( 'I' * i )
end
## New Roman Style
def new_roman num
m = ( num ) / 1000
d = ( num % 1000 ) / 500
c = ( num % 500 ) / 100
l = ( num % 100 ) / 50
x = ( num % 50 ) / 10
v = ( num % 10 ) / 5
i = ( num % 5 )
iv = 0
ix = 0
xl = 0
xc = 0
cd = 0
cm = 0
if i == 4
if v == 1
ix = 1
else
iv = 1
end
v = 0
i = 0
end
if x == 4
if l == 1
xc = 1
else
xl = 1
end
l = 0
x = 0
end
if c == 4
if d == 1
cm = 1
else
cd = 1
end
d = 0
c = 0
end
puts 'New Roman Stlye: ' +
( 'M' * m ) +
( 'CM' * cm ) +
( 'D' * d ) +
( 'CD' * cd ) +
( 'C' * c ) +
( 'XC' * xc ) +
( 'L' * l ) +
( 'XL' * xl ) +
( 'X' * x ) +
( 'IX' * ix ) +
( 'V' * v ) +
( 'IV' * iv ) +
( 'I' * i )
end
## Keeps running until nothing is inserted
puts 'Type \'quit\' to...um...quit.'
while true
puts 'Insert number to convert to Roman Numeral:'
x = gets.chomp
if x == 'quit'
break
elsif x.to_i != 0
old_roman x.to_i
new_roman x.to_i
puts
elsif x.to_i == 0
puts
puts 'ERROR'
puts '----------------------------------------'
puts 'Please insert a number larger than zero.'
puts '----------------------------------------'
puts
else
puts 'Please insert a number.'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment