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

如何将Ruby答题测验重复代码重构为类和数组结构实现复用

Ruby答题代码重构方案

方案1:公共函数抽离版本

将重复的输入校验、判分逻辑抽成独立函数,所有题目统一用数组存储,完全消除重复逻辑,新增题目只需在数组中新增配置即可:

# 获取合法的用户输入(仅接受a/b/c/d)
def get_valid_answer
  valid_options = %w[a b c d]
  loop do
    print "请输入你的答案:"
    answer = gets.chomp.downcase
    return answer if valid_options.include?(answer)
    puts "输入无效,请输入a、b、c、d中的任意一个"
  end
end

# 单题判分,返回得分(答对得1分,答错得0分)
def judge_answer(user_answer, correct_answer)
  if user_answer == correct_answer
    puts "回答正确 ✅\n\n"
    1
  else
    puts "回答错误 ❌\n\n"
    0
  end
end

def main
  score = 0
  # 所有题目统一配置
  questions = [
    {
      stem: "1. == 运算符的作用是什么?",
      options: [
        "(a) 计算算术结果",
        "(b) 为变量赋值",
        "(c) 检查两个值是否相等",
        "(d) 执行幂运算"
      ],
      correct: 'c'
    },
    {
      stem: "2. 以下哪个不属于C语言关键字?",
      options: [
        "(a) when",
        "(b) const",
        "(c) unsigned",
        "(d) volatile"
      ],
      correct: 'a'
    },
    {
      stem: "3. 函数调用时,实际参数之间用什么符号分隔?",
      options: [
        "(a) 分号",
        "(b) 冒号",
        "(c) 逗号",
        "(d) 空格"
      ],
      correct: 'c'
    }
  ]

  # 批量执行答题流程
  questions.each do |q|
    puts q[:stem]
    q[:options].each { |opt| puts opt }
    user_ans = get_valid_answer
    score += judge_answer(user_ans, q[:correct])
  end

  puts "测验结束!你的总得分是:#{score}/#{questions.size}"
end

main

方案2:面向对象封装版本

将所有答题相关逻辑封装为Quiz类,后续扩展功能(如错题收集、题目批量导入、分数排行)更便捷:

class Quiz
  def initialize
    @questions = []
    @score = 0
    @valid_options = %w[a b c d]
  end

  # 对外暴露新增题目的接口
  def add_question(stem, options, correct_answer)
    @questions << {
      stem: stem,
      options: options,
      correct: correct_answer.downcase
    }
  end

  # 获取合法输入(内部私有方法)
  private def get_valid_answer
    loop do
      print "请输入你的答案:"
      ans = gets.chomp.downcase
      return ans if @valid_options.include?(ans)
      puts "输入无效,请输入a、b、c、d中的任意一个"
    end
  end

  # 单题判分逻辑(内部私有方法)
  private def judge_question(user_ans, correct_ans)
    if user_ans == correct_ans
      @score += 1
      puts "回答正确 ✅\n\n"
    else
      puts "回答错误 ❌\n\n"
    end
  end

  # 启动测验入口
  def run
    @questions.each_with_index do |q, idx|
      puts "#{idx + 1}. #{q[:stem]}"
      q[:options].each { |opt| puts opt }
      user_ans = get_valid_answer
      judge_question(user_ans, q[:correct])
    end
    puts "测验结束!你的总得分是:#{@score}/#{@questions.size}"
  end
end

# 调用示例
if __FILE__ == $0
  quiz = Quiz.new
  # 添加题目
  quiz.add_question(
    "== 运算符的作用是什么?",
    [
      "(a) 计算算术结果",
      "(b) 为变量赋值",
      "(c) 检查两个值是否相等",
      "(d) 执行幂运算"
    ],
    'c'
  )
  quiz.add_question(
    "以下哪个不属于C语言关键字?",
    [
      "(a) when",
      "(b) const",
      "(c) unsigned",
      "(d) volatile"
    ],
    'a'
  )
  quiz.add_question(
    "函数调用时,实际参数之间用什么符号分隔?",
    [
      "(a) 分号",
      "(b) 冒号",
      "(c) 逗号",
      "(d) 空格"
    ],
    'c'
  )
  # 开始答题
  quiz.run
end

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 17:48:03