0

我有一个 Ruby 哈希(最初是 rails 中的一个参数)

我如何计算correctness每个中的数量answers_attributes

(我这样做的原因是我试图通过rails创建一个多项选择测验。一个问题可能有很多答案。我试图使用multi_correct复选框来决定哪个问题有很多正确答案。但这有点违反直觉。所以我希望后端通过计算每个问题的正确性来决定)

{
  "utf8" => "✓", "authenticity_token" => "r5xX46JG/GPF6+drEWmMPR+LpOI0jE0Tta/ABQ0rZJJE+UbbEjvNMLP6y2Z9IsWlXq27PR6Odx0EK4NECPjmzQ==", "question_bank" => {
    "name" => "123213", "questions_attributes" => {
      "0" => {
        "content" => "question 1", "multi_correct" => "no", "answers_attributes" => {
          "0" => {
            "content" => "as1", "correctness" => "false"
          }, "1" => {
            "content" => "as2", "correctness" => "false"
          }, "2" => {
            "content" => "as3", "correctness" => "true"
          }, "3" => {
            "content" => "as4", "correctness" => "false"
          }
        }
      }, "1" => {
        "content" => "q2", "multi_correct" => "no", "answers_attributes" => {
          "0" => {
            "content" => "a1", "correctness" => "false"
          }, "1" => {
            "content" => "a2", "correctness" => "false"
          }, "2" => {
            "content" => "a3", "correctness" => "true"
          }, "3" => {
            "content" => "a4", "correctness" => "false"
          }
        }
      }, "2" => {
        "content" => "q3", "multi_correct" => "no", "answers_attributes" => {
          "0" => {
            "content" => "aa1", "correctness" => "false"
          }, "1" => {
            "content" => "aa2", "correctness" => "false"
          }, "2" => {
            "content" => "aa3", "correctness" => "false"
          }, "3" => {
            "content" => "aa4", "correctness" => "true"
          }
        }
      }
    }
  }, "commit" => "Submit"
}
4

2 回答 2

2

我将此解释为寻找每个问题的正确答案的数量。如果是这样,您可以使用以下方法实现此目的:

your_hash['question_bank']['questions_attributes'].values.reduce(Hash.new(0)) do |hash, question| 
  question['answers_attributes'].each do |_k, answer| 
    hash[question['content']] += 1 if answer['correctness'] == 'true'
  end
  hash
end

这给出了结果:

# => {"question 1"=>1, "q2"=>1, "q3"=>1}

基本上,代码的作用是:

  • 遍历问题,reduce用于生成默认值为0available的哈希
  • 循环遍历此问题的答案,并在答案正确时添加1到随附hash[question_name](或示例中)hash[question['content']]
  • 返回随附的哈希

如果您正在使用 Rails,参数的引用可能暗示了这一点,请考虑使用each_with_object而不是reduce; 这样您就可以避免hash示例中的尾随,因为它总是返回累加器。

希望对您有所帮助 - 如果您有任何问题,请告诉我。

于 2018-08-14T12:08:44.730 回答
1

如果您只想计算哈希中有多少正确答案,您可以使用它inject来执行此操作。这是一种方法:

# iterate over the questions
hash['question_bank']['questions_attributes'].values.inject(0) do |count, q|
  # iterate over the answers
  count += q['answers_attributes'].values.inject(0) do |a_count, a|
    a_count += a['correctness'] == 'true' ? 1 : 0
  end
end
于 2018-08-14T11:51:31.313 回答