数组无法强制转换为Fixnum(TypeError)

时间:2015-05-08 14:47:08

标签: ruby 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:在+': Array can't be coerced into Fixnum (TypeError) from assignment1.rb:22:in块中'       from assignment1.rb:7:in each' from assignment1.rb:7:in'       来自assignment1.rb:1:在''

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

需要帮助。提前谢谢。

2 个答案:

答案 0 :(得分:3)

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]

用逗号代替分号。

答案 1 :(得分:0)

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

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