Skip to content
This repository was archived by the owner on Mar 26, 2019. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions bin/calculator
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,5 @@ class_b = ARGV[3]
number_b = ARGV[4]
mode = ARGV[5].to_s || 'arabic'

first = class_a.constantize.new(number_a)
puts first.send(operator, class_b.constantize.new(number_b))
first = class_a.constantize.new(number_a, mode)
puts first.send(operator, class_b.constantize.new(number_b, mode))
40 changes: 37 additions & 3 deletions lib/converter.rb → lib/sa_converter.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
class SAConverter

INT_VAL = {
INT_VAL = {
'I' => 1,
'V' => 5,
'X' => 10,
Expand All @@ -10,12 +10,26 @@ class SAConverter
'M' => 1000
}

def initialize(roman)
ROMAN_VAL = INT_VAL.invert

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


def initialize(roman, mode='arabic')
@roman = roman
@mode = mode
end

def +(other)
self.to_i + other.to_i
result = self.to_i + other.to_i
@mode == 'arabic' ? result : to_roman(result)
end

def -(other)
Expand All @@ -30,6 +44,26 @@ def /(other)
self.to_i / other.to_i
end

def lookup
@lookup ||= Hash[(ROMAN_VAL.merge SPECIAL).sort.reverse]
end

def to_roman(val)
result = ''
while val > 0
k, v = *find_largest(val)
val -= k
result << v
end
result
end

def find_largest(val)
lookup.each do |k, v|
return [k,v] if k <= val
end
end

# Use this method to convert roman numbers to arabic
#
# Don't you dare cheat on spec!!!
Expand Down
2 changes: 1 addition & 1 deletion spec/lib/converter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
roman = conversion[1]

it "converts #{roman} to #{arabic}" do
expect(described_class.convert(roman)).to eq arabic
expect(described_class.new(roman).to_i).to eq arabic
end
end
end