【问题标题】:Array cannot be coerced into Fixnum (TypeError)无法将数组强制转换为 Fixnum (TypeError)
【发布时间】:2015-05-08 14:47:08
【问题描述】:

我写了一个基本的计算程序。该程序对于某些输入运行良好,而为其他输入提供 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 ' 来自 assignment1.rb:7:in each' from assignment1.rb:7:in' 来自 assignment1.rb:1:in `'

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

需要帮助。提前致谢。

【问题讨论】:

  • 旁注:顺便说一句,你的算法不正确。介词中的数字将被减去。
  • 是的,我最终必须将它纳入我的算法中,实际上是一步一步进行的,有很多东西要实现。

标签: ruby typeerror


【解决方案1】:
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]

用逗号代替分号。

【讨论】:

  • 我也建议result += const_get(i)
  • 很好的建议.. 减少了我的代码行 :) 谢谢@mudasobwa
  • @Niyanta 我建议使用injectreduce 而不是for 的哈希结构和更红的循环。在没有类定义的情况下,我已将您的代码减少到 3 行
【解决方案2】:

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

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

【讨论】:

  • 我使用常量是因为我必须强调它们是我程序中的常量值。否则,您的解决方案将是完美的。谢谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多