Module: CousinRoman::Roman

Extended by:
Roman
Included in:
Roman
Defined in:
lib/cousin_roman/roman.rb

Instance Method Summary collapse

Instance Method Details

#convert(number) ⇒ Object

Convert Roman number represented as a string to an Integer.

It is essential that numer is a valid Roman numeral.

The steps are:

  1. Replace factors with their numeric values

starting from subtractive factors (cause they are compound).

  1. Sum this numeric values to get the final answer



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/cousin_roman/roman.rb', line 21

def convert(number)
  intermediate = number.dup.downcase
  SUBTRACTIVES.each do |factor, value|
    intermediate.gsub!(factor, "(#{value})")
  end
  ONES.merge(FIVES).each do |factor, value|
    intermediate.gsub!(factor, "(#{value})")
  end

  intermediate.scan(/\((\d*)\)/).reduce(0) do |sum, term|
    sum + term.first.to_i
  end
end

#roman_regexObject



49
50
51
# File 'lib/cousin_roman/roman.rb', line 49

def roman_regex
  /^(M{0,3})(D?C{0,3}|C[DM])(L?X{0,3}|X[LC])(V?I{0,3}|I[VX])$/i
end

#to_arabian(number) ⇒ Object



35
36
37
38
# File 'lib/cousin_roman/roman.rb', line 35

def to_arabian(number)
  clean = number.strip
  convert clean if valid? clean
end

#to_arabian!(number) ⇒ Object



40
41
42
43
44
45
46
47
# File 'lib/cousin_roman/roman.rb', line 40

def to_arabian!(number)
  clean = number.strip
  if valid? clean
    convert clean
  else
    raise TypeError, 'not a valid roman number'
  end
end

#valid?(number) ⇒ Boolean

Returns:

  • (Boolean)


7
8
9
10
# File 'lib/cousin_roman/roman.rb', line 7

def valid?(number)
  matches = number.match roman_regex
  matches and !matches[0].empty?
end