I'm doing a Ruby Kata (Roman numeral converter) and I'm trying to separate my code out so it's not one huge block.
Here is what I have so far:
def roman s
total = convert s[0,1]
(0..s.length).each do |i|
case convert (s[i+1,1]).to_i >= convert (s[i,1])
when true : total += convert s[i+1,1]
when false: total -= convert s[i+1,1]
end
end
total
end
def convert s
case s
when 'I' : 1
when 'V' : 5
when 'X' : 10
when 'L' : 50
when 'C' : 100
when 'D' : 500
when 'M' : 1000
else 0
end
I want to move the case statement in the roman method, so it would now look like this:
case preceding_number_is_lower_than_next_number s,i
Along with adding the method:
def preceding_number_is_lower_than_next_number s,i
convert (s[i+1,1]).to_i >= convert (s[i,1])
end
However, when I do that, and give it the input 'XXXI' it changes from giving the correct output of 29, to the incorrect output of 10.
Since it's the exact same code running, just refactored, I can't imagine why the behavior changes.
Any ideas?