gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 08:45:26 25 4
gpt4 key购买 nike

我已经写了一个基本的计算程序。该程序对某些输入运行良好,而对其他输入则给出 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:in
block 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]

用逗号代替分号。

关于ruby - 不能将数组强制转换为 Fixnum (TypeError),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30126659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com