Module: CousinRoman::Roman
Instance Method Summary collapse
-
#convert(number) ⇒ Object
Convert Roman
number
represented as a string to an Integer. - #roman_regex ⇒ Object
- #to_arabian(number) ⇒ Object
- #to_arabian!(number) ⇒ Object
- #valid?(number) ⇒ Boolean
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:
-
Replace factors with their numeric values
starting from subtractive factors (cause they are compound).
-
Sum this numeric values to get the final answer
19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/cousin_roman/roman.rb', line 19 def convert(number) intermediate = number.dup.downcase compound = braketize_value_of SUBTRACTIVES singular = braketize_value_of ONES.merge(FIVES) [compound, singular].each { |factors| factors.each { |literal, val| intermediate.gsub!(literal, val) } } intermediate.scan(/\((\d*)\)/).reduce(0) do |sum, term| sum + term.first.to_i end end |
#roman_regex ⇒ Object
42 43 44 |
# File 'lib/cousin_roman/roman.rb', line 42 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
31 32 33 34 |
# File 'lib/cousin_roman/roman.rb', line 31 def to_arabian(number) clean = number.strip convert clean if valid? clean end |
#to_arabian!(number) ⇒ Object
36 37 38 39 40 |
# File 'lib/cousin_roman/roman.rb', line 36 def to_arabian!(number) clean = number.strip valid? clean or raise TypeError, 'not a valid roman number' convert clean end |
#valid?(number) ⇒ Boolean
5 6 7 8 |
# File 'lib/cousin_roman/roman.rb', line 5 def valid?(number) matches = number.match roman_regex matches and !matches[0].empty? end |