vendredi 8 mai 2015

Array cannot be coerced into Fixnum (TypeError)

I have written a basic program of calculations. The program runs fine for some input, while gives TypeError for others. I can't figure out the reason behind this unpredictable behavior. Here's my code -

class Conversion
I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000
result = 0
puts "enter the string"
input = gets.chomp.upcase
temp = input.split(//)
for i in temp do
    case i
        when 'M'
            result = result + M
        when 'D'
            result = result + D
        when 'C'
            result = result + C
        when 'L'
            result = result + L
        when 'X'
            result = result + X
        when 'V'
            result = result + V
        when 'I'
            result = result + I
        end
   end
   puts result
end

The error log is as-

assignment1.rb:22:in +': Array can't be coerced into Fixnum (TypeError) from assignment1.rb:22:inblock in ' from assignment1.rb:7:in each' from assignment1.rb:7:in' from assignment1.rb:1:in `'

Now, when I supply input like mxcd, dcm, lxv etc it works fine. But for inputs like xvi, ivx, icd it gives TypeError.

Need help with it. Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire