From: Kelly Tanguay Date: 2008-02-03T04:33:00+09:00 Subject: Re: Learn to Program, by Chris Pine This is my take on the same problem: def roman_num number set1 = [ 1, 5, 10, 50, 100, 500, 1000 ] set2 = [ 'I', 'V', 'X', 'L', 'C', 'D', 'M' ] numeral = [] while number > 0 if (number/(set1.last)) >= 1 roman = (number/(set1.last)) numeral.push((set2.pop)*roman) number = (number%(set1.pop)) else set2.pop set1.pop end end puts 'Old Roman Numeral is ' + numeral.join + '.' end puts 'Please enter a number to see what it is in old roman numerals.' number = gets.chomp.to_i while number < 1 || number > 3999 puts 'Please enter a number between 1 and 3999' number = gets.chomp.to_i end roman_num number Jan_K wrote: > Chapter 9, exercise 2 (page 76) > > Old-school Roman numerals. In the early days of Roman numerals, > the Romans didn?t bother with any of this new-fangled subtraction > IX nonsense. No sir, it was straight addition, biggest to littlest - > so 9 was written VIIII, and so on. Write a method that, when > passed an integer between 1 and 3000 (or so), returns a string > containing the proper old-school Roman numeral. In other words, > old_roman_numeral 4 should return 'IIII'. Make sure to test > your method on a bunch of different numbers. Hint: Use the integer > division and modulus methods on page 36. > For reference, these are the values of the letters used: > I = 1 V = 5 X = 10 L = 50 > C = 100 D = 500 M = 1000 > > > Solution: > ---------------------------------------------------------------- > def old_roman_number input > > while input < 1 || input > 3999 > puts 'Please enter a number between 1 and 3999' > input = gets.chomp.to_i > end > > m_mod = input%1000 > d_mod = input%500 > c_mod = input%100 > l_mod = input%50 > x_mod = input%10 > v_mod = input%5 > > m_div = input/1000 > d_div = m_mod/500 > c_div = d_mod/100 > l_div = c_mod/50 > x_div = l_mod/10 > v_div = x_mod/5 > i_div = v_mod/1 > > m = 'M' * m_div > d = 'D' * d_div > c = 'C' * c_div > l = 'L' * l_div > x = 'X' * x_div > v = 'V' * v_div > i = 'I' * i_div > > puts m + d + c + l + x + v + i > > end > > number = gets.chomp.to_i > old_roman_number(number) -- Posted via http://www.ruby-forum.com/.