# Create new hash
roman_numeral = { }
status = 'invalid'
# Defining the roman numeral hash
roman_numeral['I'] = 1
roman_numeral['V'] = 5
roman_numeral['X'] = 10
roman_numeral['L'] = 50
roman_numeral['C'] = 100
roman_numeral['D'] = 500
roman_numeral['M'] = 1000
while status != 'valid'
# Request a Roman numeral, capitalize input and put in array
puts 'Please input a Roman Numeral'
input_numeral = gets.chomp.upcase
no_of_chars = input_numeral.length
input_array = [ ]
counter1 = 0
while counter1 < no_of_chars
input_array.push input_numeral[counter1]
counter1 = counter1 + 1
end
# Check each character in the array to see if its a Roman Numeral
counter2 = 0
input_array.each do |input_letter|
roman_numeral.each do |rom_letter,number|
if input_letter.chr == rom_letter
counter2 = counter2 + 1
else
end
end
end
if counter2 == input_array.length
status = 'valid'
else
status = 'invalid'
puts 'Error: Not all characters are valid roman numerals'
end
end
# Convert roman numeral letter array to array of numbers
number_array = [ ]
input_array.each do |letter|
letter = letter.chr
number = roman_numeral[letter]
number_array.push number
end
# Add/Subtract number array one at a time starting from right
counter3 = number_array.length - 1
# Starting value, first number
number = number_array[counter3]
counter3 = counter3 - 1
while counter3 > -1
# Sum from left to right
if number_array[counter3] < number_array[counter3+1]
number = number - number_array[counter3]
else
number = number + number_array[counter3]
end
counter3 = counter3 - 1
end
puts number
2. Birthday Helper
# Program needs .txt input file.
filename = 'birthdays.txt'
birth_dates = { }
File.open filename do |f|
f.each_line do |entry|
date = entry[-13..-1]
name = entry[0..-15]
birth_dates[name] = date
end
end
puts 'Enter a name and their next birthday will be returned'
name = gets.chomp
date = birth_dates[name]
year = date[-5..-1].to_i
day = date[-9,2].to_i
month_string = date[-13,3]
if month_string == 'Jan'
month = 1
elsif month_string == 'Feb'
month = 2
elsif month_string == 'Mar'
month = 3
elsif month_string == 'Apr'
month = 4
elsif month_string == 'May'
month = 5
elsif month_string == 'Jun'
month = 6
elsif month_string == 'Jul'
month = 7
elsif month_string == 'Aug'
month = 8
elsif month_string == 'Sep'
month = 9
elsif month_string == 'Oct'
month = 10
elsif month_string == 'Nov'
month = 11
elsif month_string == 'Dec'
month = 12
end
today = Time.new
birthdate = Time.mktime(year,month,day)
birthday = Time.mktime(2008,month,day)
if birthday < today
next_birthday = Time.mktime(2009,month,day)
age = (next_birthday - birthdate)/(60*60*24*365)
age = age.to_i
puts name + '\'s next birthday will be ' + next_birthday.to_s
puts 'and they will be ' + age.to_s + ' years old'
else
age = (birthday - birthdate)/(60*60*24*365)
age = age.to_i
puts name + '\'s next birthday will be ' + birthday.to_s
puts 'and they will be ' + age.to_s + ' years old'
end