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

如何在Ruby中验证选择题命令行输入的有效性?

解决选择题测验程序的输入验证问题

你的代码当前的输入验证逻辑存在局限性,仅能过滤字典序大于"d"的单个字符,无法覆盖以下无效输入场景:

  • 多字符输入(如"ab")
  • 数字、符号输入(如"1")
  • 大写字母输入(如"Z")
  • 空输入(直接按回车)

修改后的代码

question = "What is the last letter in alphabet?\n(a) Y\n(b) R\n(c) Z\n(d) Q"

puts question
answer = gets.chomp.downcase
while !["a", "b", "c", "d"].include?(answer)
  puts "Please enter a, b, c, or d"
  puts
  puts question
  answer = gets.chomp.downcase
end

# 可选:添加答案判断逻辑
if answer == "c"
  puts "Correct!"
else
  puts "Wrong answer. The correct option is (c) Z."
end

关键改进点

  1. 统一输入格式:使用downcase将输入转为小写,兼容用户输入大写字母的情况;chomp移除输入末尾的换行符,同时处理直接回车的空输入场景。
  2. 全面的有效性检查:通过!["a", "b", "c", "d"].include?(answer)判断输入是否属于有效选项集合,只要不在集合内就触发重新输入,覆盖所有无效情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 16:05:24