From: Hung Dao Date: 2006-12-10T20:53:30+09:00 Subject: Re: Need help on a program class Integer def to_roman Hash["M", 1000, "D", 500, "C", 100, "L", 50, "X", 10, "V", 5, "I",1].sort_by{|a| -a.last}.inject( [ "", self ] ){|roman, pair| [ (pair.last - roman.last ==1 )? roman.first+"I"+pair.first :roman.first + pair.first * (roman.last / pair.last), roman.last % pair.last ] }. first endend I noticed that your code is partly wrong since it will output IIII for4 and so on , I have modified it a little bit , but I have not checkedthe result RegardsOn 12/9/06, William James wrote:> Christopher Latif wrote:> > Stuck on this exercise from a book:> > 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.> > For reference, these are the values of the letters used:> > I =1 V =5 X = 10 L = 50> > C = 100 D = 500 M = 1000> >> > Suggestions on a soloution?> >> > --> > Posted via http://www.ruby-forum.com/.>> class Integer> def to_roman> "I =1 V =5 X = 10 L = 50> C = 100 D = 500 M = 1000".> scan( / ([A-Z]) \s *= \s* (\d+) /x ).> map{|letter,val| [ letter, val.to_i ] }.> sort_by{|a| -a.last}.> inject( [ "", self ] ){|roman, pair|> [ roman.first + pair.first * (roman.last / pair.last),> roman.last % pair.last ] }.> first> end> end>>> -- Chỉ có lý trí của bản thân mới soi sáng được sự thật."Cái đẹp đẽ nhấtmà chúng ta có thể trải nghiệm được là cái bí ẩn. Đó là cảm thức nềntảng trong cái nôi của nghệ thuật và khoa học chân chính. Kẻ nào khôngbiết đến nó, không còn khả năng ngạc nhiên hay kinh ngạc, kẻ đó coinhư đã chết, đã tắt rụi lửa sống trong mắt mình""Das Schönste, was wirerleben können, ist das Geheimnisvolle. Es ist das Grundgefühl, das ander Wiege von wahrer Kunst und Wissenschaft steht. Wer es nicht kenntund sich nicht mehr wundern, nicht mehr staunen kann, der istsozusagen tot und sein Auge erloschen.""The fairest thing we canexperience is the mysterious. It is the fundamental emotion whichstands at the cradle of true art and true science. He who knows it notand can no longer wonder, no longer feel amazement, is as good asdead, his eyelight has been extinct."