O'Reilly logo

Ruby by Example by Kevin C. Baird

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

#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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required