Ruby 无法将数组强制转换为Fixnum(TypeError)
我已经写了一个基本的计算程序。对于某些输入,程序运行良好,而对于其他输入,程序则给出TypeError。我想不出这种不可预测的行为背后的原因。这是我的密码-Ruby 无法将数组强制转换为Fixnum(TypeError),ruby,typeerror,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
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+':无法将数组强制为Fixnum(TypeError)
from assignment1.rb:22:in
block in'
来自assignment1.rb:7:in每个'
从分配1.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]
用逗号代替分号。为什么不使用散列而不是一堆常量,如下所示:
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
旁注:顺便说一句,你的算法不正确。介词中的数字要减去更高的数字。是的,我最终必须将其纳入我的算法中,实际上是一步一步地进行的,有很多东西要在这个算法中实现。我建议
result+=const_get(I)
。非常好的建议。。减少了我的代码行:)谢谢@mudasobwa@Niyanta我建议使用inject
或reduce
而不是for
使用一个哈希结构和一个更rubyesque的循环。我已经把你的代码减少到3行,没有类定义。我使用常量,因为我必须强调它们是我程序中的常量值。否则,你的解决方案将是完美的。谢谢:)