You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Ruby程序读取输入数字至输入'end'后计算总和?

Fixing Your Ruby Number Sum Program

Hey there! Let's get your program working correctly. I'll break down the issues in your code first, then show you a couple of simple, working versions tailored for a new programmer. 😊

What was off with your original code?

  • You only read input once at the start (a=gets.to_s), so the loop would keep reusing that first value forever instead of asking for new input each time.
  • The while a=a.to_s condition always stays true (non-empty strings count as "true" in Ruby), so the loop would never stop on its own—only if it hits the break.
  • Your puts n comes right after break—once you break out of the loop, that line never gets to run!

Working Version 1 (Using loop - super easy to read)

sum = 0

loop do
  # Get input and remove the extra newline character with chomp
  input = gets.chomp

  # Stop the loop immediately if user types "end"
  break if input == "end"

  # Convert input to integer and add to our total sum
  sum += input.to_i
end

# Print the final sum after the loop finishes
puts "Total sum: #{sum}"

Working Version 2 (Using while loop if you prefer that style)

If you'd rather stick with a while loop, here's how to structure it properly:

sum = 0
input = ""

while input != "end"
  input = gets.chomp
  # Only add to sum if the input isn't "end"
  sum += input.to_i unless input == "end"
end

puts "Total sum: #{sum}"

Quick tips to remember:

  • Use gets.chomp to clean up user input—it removes the hidden newline character that gets added when you press Enter.
  • Always read new input inside the loop, so the program asks for a fresh value every time it runs through the loop.
  • Calculate the sum only when the input is a number, and print the final total after the loop has finished.

内容的提问来源于stack exchange,提问作者Lampob02

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:57:25