This code is supposed to update the total within the loop, but when I put the total when its broken it doesn't update.
total = 0
while true do
puts "Give me a number"
input = gets.chomp
if input == Integer
total = input
elsif input == "stop"
puts total
break
end
end
CodePudding user response:
input = gets.chomp
will result String
class. So your logic on if input == Integer
it will never be reached. you need to convert it to integer using to_i
and input == Integer
i never used that kind of syntax to check the classes, i rather use input.is_a?(String)
. but if you convert to integer first it will never check stop
string condition. so maybe
total = 0
while true do
puts "Give me a number"
input = gets.chomp
if input == "stop"
puts total
break
end
total = input.to_i
end
CodePudding user response:
As mentioned in the above comment by mu is too short and dedypuji's answer you have a couple of issue. Here is another variation that I think will work and I think is a little more ruby idiomatic.
total = 0
loop do
print "Give me a number: "
input = gets
break if /stop|^$/ =~ input
total = input.to_i
end
puts total