module English::RomanNumerals

Contains methods to convert integers to roman numeral strings and vice-versa.

Constants

LOOKUP
MAX

The largest integer representable as a roman numerable by this module.

NUMBERS
PAIR_NUMBERS
PAIR_SYMBOLS
PAIR_TABLE

{

'CM' => 900,
'CD' => 400,
'XC' => 90,
'XL' => 40,
'IX' => 9,
'IV' => 4

}

REGEXP

Stolen from O'Reilly's Perl Cookbook 6.23. Regular Expression Grabbag.

SYMBOLS
TABLE

Maps roman numeral digits to their integer values.

{
  'I' => 1,
  'V' => 5,
  'X' => 10,
  'L' => 50,
  'C' => 100,
  'D' => 500,
  'M' => 1000,
}

Public Class Methods

arabic(roman_string)
Alias for: to_integer
from_integer(integer) click to toggle source

Converts integer to a roman numeral.

# File lib/more/facets/roman.rb, line 73
def from_integer(integer)
  return nil if integer < 0 || integer > MAX

  r = integer  # remainder
  y = ''       # result

  NUMBERS.each do |n|
    while r >= n
      r -= n
      y += LOOKUP[n]
    end
    break if r <= 0
  end

  return y
end
Also aliased as: roman
is_roman_numeral?(string) click to toggle source

Returns true iif string is a roman numeral.

# File lib/more/facets/roman.rb, line 120
def is_roman_numeral?(string)
  REGEXP =~ string
end
roman(integer)
Alias for: from_integer
to_integer(roman_string) click to toggle source

Converts roman_string, a roman numeral, to an integer

# File lib/more/facets/roman.rb, line 94
def to_integer(roman_string)
  return nil unless roman_string.is_roman_numeral?

  l = nil  # last
  i = 0    # integer result

  c = roman_string.to_s.upcase.split(//).reverse

  c.each do |d|
    if v = TABLE[d]
      if l && l > v
        i -= v
      else
        i += v
      end
      l = v
    end
  end

  return i
end
Also aliased as: arabic