基本问题 Ruby;为什么总变量在循环中没有更新
这段代码应该更新循环内的总数,但是当我在损坏时放置总数时,它不会更新。
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
input = gets.chomp
将生成String
类。因此,您的逻辑if input == Integer
永远不会达到。你需要使用to_i
和input == Integer
将其转换为整数我从来没有使用过这种语法来检查类,我宁愿使用input.is_a? (字符串)
。但如果您首先转换为整数,它将永远不会检查stop
字符串条件。所以也许input = gets.chomp
will resultString
class. So your logic onif input == Integer
it will never be reached. you need to convert it to integer usingto_i
andinput == Integer
i never used that kind of syntax to check the classes, i rather useinput.is_a?(String)
. but if you convert to integer first it will never checkstop
string condition. so maybe正如 mu 太短 和 dedypuji 的回答中提到的,您有几个问题。这是我认为可行的另一种变体,并且我认为它更符合 ruby 习惯。
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.