/ruby/roman-numerals/roman.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Fixnum
  def to_roman
    thousands + hundreds + tens + ones
  end

private
  def ones
    ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'][self % 10]
  end

  def tens
    ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'][(self % 100)/10]
  end

  def hundreds
    ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'][(self % 1000)/100]
  end

  def thousands
    ['', 'M', 'MM', 'MMM'][(self % 10000)/1000]
  end
end

Comments

Now with private methods.

helenst commented 27 January 2015 at 21:18 UTC

You're not logged in right now. Please login via GitHub to comment