Ruby/ RoR - 针对关联数组循环对象数组

发布于 2024-10-08 06:28:08 字数 666 浏览 0 评论 0原文

我有一个问题 @questions 对象数组

--- 
- !ruby/object:Question 
  attributes: 
    id: "1"
    answer: "2"
- !ruby/object:Question 
  attributes: 
    id: "7"
    answer: "1"
- !ruby/object:Question 
  attributes: 
    id: "6"
    answer: "4"
- !ruby/object:Question 
  attributes: 
    id: "4"
    answer: "1"

和一个答案数组 @answers

--- !map:ActiveSupport::HashWithIndifferentAccess 
"1": "2"
"7": "3"
"6": "4"
"4": "0"

我如何使用任何循环机制验证问题的答案?

在上面的示例中,只有第一个问题的答案是正确的,我需要将其作为数组输出,如下所示

--- !map:ActiveSupport::HashWithIndifferentAccess 
"1": true
"7": false
"6": false
"4": false

I h've an array of object of Questions @questions

--- 
- !ruby/object:Question 
  attributes: 
    id: "1"
    answer: "2"
- !ruby/object:Question 
  attributes: 
    id: "7"
    answer: "1"
- !ruby/object:Question 
  attributes: 
    id: "6"
    answer: "4"
- !ruby/object:Question 
  attributes: 
    id: "4"
    answer: "1"

And an Array of Answers @answers

--- !map:ActiveSupport::HashWithIndifferentAccess 
"1": "2"
"7": "3"
"6": "4"
"4": "0"

How can i validate Answers against Questions with any loop mechanism?

In the above example only the answer for the first question is correct, i need to get out put as an array like one below

--- !map:ActiveSupport::HashWithIndifferentAccess 
"1": true
"7": false
"6": false
"4": false

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦回梦里 2024-10-15 06:28:08
questions = [{id: 1, answer: 2},{id: 7, answer: 1},{id: 6, answer: 4},{id: 4, answer: 1}]
#=> [{:id=>1, :answer=>2}, {:id=>7, :answer=>1}, {:id=>6, :answer=>4}, {:id=>4, :answer=>1}]
answers = {1 => 2, 7 => 3, 6 => 4, 4 => 0}
#=> {1=>2, 7=>3, 6=>4, 4=>0}
# map to a true/false array, based on whether the answer was correct
questions.map{|a| a[:answer] == answers[a[:id]]}
#=> [true, false, true, false]
# add question ids to the above array:
questions.map{|a| [a[:id], a[:answer] == answers[a[:id]]]}
#=> [[1, true], [7, false], [6, true], [4, false]]
# make a hash out of it:
Hash[questions.map{|a| [a[:id], a[:answer] == answers[a[:id]]]}]
#=> {1=>true, 7=>false, 6=>true, 4=>false}
questions = [{id: 1, answer: 2},{id: 7, answer: 1},{id: 6, answer: 4},{id: 4, answer: 1}]
#=> [{:id=>1, :answer=>2}, {:id=>7, :answer=>1}, {:id=>6, :answer=>4}, {:id=>4, :answer=>1}]
answers = {1 => 2, 7 => 3, 6 => 4, 4 => 0}
#=> {1=>2, 7=>3, 6=>4, 4=>0}
# map to a true/false array, based on whether the answer was correct
questions.map{|a| a[:answer] == answers[a[:id]]}
#=> [true, false, true, false]
# add question ids to the above array:
questions.map{|a| [a[:id], a[:answer] == answers[a[:id]]]}
#=> [[1, true], [7, false], [6, true], [4, false]]
# make a hash out of it:
Hash[questions.map{|a| [a[:id], a[:answer] == answers[a[:id]]]}]
#=> {1=>true, 7=>false, 6=>true, 4=>false}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文