不能将数组强制转换为 Fixnum (TypeError)

Array cannot be coerced into Fixnum (TypeError)

我写了一个基本的计算程序。该程序对某些输入运行良好,而对其他输入则给出 TypeError。我无法弄清楚这种不可预测的行为背后的原因。这是我的代码 -

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

错误日志如下-

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 `'

现在,当我提供 mxcd、dcm、lxv 等输入时,它工作正常。但是对于像 xvi、ivx、icd 这样的输入,它会给出 TypeError。

需要帮助。提前致谢。

I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000

被解释为

I = ( 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000)

导致

I = [1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000]

用逗号代替分号。

为什么不使用 Hash 而不是像这样的一堆常量:

class Conversion
  CONVERSIONS ={'I' => 1, 'V' => 5, 'X' => 10, 'L' => 50, 'C' => 100, 'D' => 500, 'M' => 1000}.freeze
  puts "enter the string"
  gets.chomp.upcase.split(//).inject(0) { |sum, i| sum + CONVERSIONS[i].to_i }
end