Reputation: 473
I have written a basic program of calculations. The program runs fine for some input, while gives TypeError for others. I can't figure out the reason behind this unpredictable behavior. Here's my code -
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
The error log is as-
assignment1.rb:22:in
+': Array can't be coerced into Fixnum (TypeError) from assignment1.rb:22:in
block in ' from assignment1.rb:7:ineach' from assignment1.rb:7:in
' from assignment1.rb:1:in `'
Now, when I supply input like mxcd, dcm, lxv etc it works fine. But for inputs like xvi, ivx, icd it gives TypeError.
Need help with it. Thanks in advance.
Upvotes: 2
Views: 4019
Reputation: 29308
Why not use a Hash instead of a bunch of constants like so:
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
Upvotes: 0
Reputation: 80065
I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000
is interpreted as
I = ( 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000)
resulting in
I = [1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000]
Substitute the comma's for semicolons.
Upvotes: 3