0

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?

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
user1029167
  • 349
  • 1
  • 4
  • 15
  • 1
    Consider putting parens around your arguments in all but the very simplest cases. It can hide a lot of bugs (I don't know if it is here...) – Chowlett Jun 27 '12 at 13:27
  • Also, no spaces between argument parameters parenthesis and the method name. And please give us one complete version of your final code. And please use some more correct form. – Linuxios Jun 27 '12 at 13:34

0 Answers0