I’m working on an exercise where I have to create a roman to arabic number converter. As far as I can tell, the code below is totally kosher, but I keep getting an error when I run my tests. Ruby thinks there’s an undefined method or variable on line 37 (noted by comment below).
I’m wondering if my snytax is off or if it’s something else. Suggestions?
class ArabicNumeral
def replace_troublesome_roman_numerals(letters)
tough_mappings = {"CM" => "DCCCC", "CD" => "CCCC", "XC" => "LXXXX", "XL" => "XXXX", "IX"=> "VIIII", "IV" => "IIII"}
tough_mappings.each { |roman, arabic| letters = letters.gsub(roman, arabic) }
letters
end
def convert_and_add(letters)
digits = { "M" => 1000, "CM" => 900, "D" => 500, "C" => 100, "XC" => 90, "L" => 50, "XL" => 40, "X" => 10, "IX" => 9, "V" => 5, "IV" => 4, "I" => 1}
letters = letters.split("")
letters.inject(0) do |sum, letter|
arabic = digits[letter]
sum += arabic
end
end
def self.convert(letters)
roman_string = replace_troublesome_roman_numerals(letters) ###LINE 37!
arabic_number = convert_and_add(roman_string)
arabic_number
end
end
The problem here is the method you are calling on line 37.
replace_troublesome_roman_numerals(letters). The problem is the methodself.convert(letters)is a class method. You can call it like this:However, it contains a call to an instance variable (being that
replace_troublesome_roman_numerals(letters)I mentioned earlier.This creates an instance of
ArabicNumeraland calls the method you need without saving it to a variable and taking up memory. I also removed the variablearabic_numberfrom your method because you are callingconvert_and_add(roman_string), adding it to the variable, and then returning the variable. sinceconvert_and_add(roman_string)is the last thing handled by the method, it will return this anyway without the variable.If you never plan on using those methods in an instance of
ArabicNumeralthen I would suggest making all the methods class level or wrapping them in aModulethat you would include in your projects. If you don’t plan on using them outside of theArabicNumeralclass at all, consider putting them behind aprotectedorprivatewhile leavingconvert(letters)available.