From: Todd Benson Date: 2008-02-03T11:49:13+09:00 Subject: Re: Learn to Program, by Chris Pine On Feb 2, 2008 7:47 PM, Todd Benson wrote: > > Just for fun. Certainly not great for speed for large numbers, but the > integer max was low so... > > H = Hash[*(([1,5,10,50,100,500,1000].zip %w|I V X L C D M|).flatten)] > def roman(n, s="") > H.keys.sort.reverse.each do |k| > s << (H[k] * (n / k)) > n %= k > end > s > end > puts roman(ARGV[0].to_i) > > The usage would simply be "ruby .rb " > > I'm sure someone could come up with a one-liner, though. Actually, better production code that keeps in line with OO concepts would be... class Integer ROMAN = { 1 => "I", 5 => "V", 10 => "X", 50 => "L", 100 => "C", 500 => "D", 1000 => "M" } def roman number, roman_string = self, "" ROMAN.keys.sort.reverse.each do |key| roman_string << (ROMAN[n] * (number/key) n %= key end roman_string end end #usage puts 2137.roman # => "MMCCCXVII" I'm pretty sure there were better and more thorough examples at http://www.rubyquiz.com/quiz22.html. Todd