#17 Roman Numerals (roman_numeral.rb)

In the previous script, you learned how to change the representation of a number as a String so that it had commas (or some other desired delimiting character) in appropriate places for easier readability. One of the most traditional ways to represent a number as a String is as a Roman numeral. This script adds a new method to all Integers called to_roman. Let’s see it in action in irb.

$ irb -r roman_numeral.rb
irb(main):001:0> 42.to_roman
=> "XLII"
irb(main):002:0> 1.to_roman
=> "I"
irb(main):003:0> 5.to_roman
=> "V"
irb(main):004:0> digits = (0..9).to_a
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
irb(main):005:0> digits.map { |d| d.to_roman }
=> ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]

If you remember ...

Get Ruby by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.