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

时间:2010-12-20 07:07:37

标签: ruby-on-rails ruby loops

我有一系列问题对象@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

1 个答案:

答案 0 :(得分:1)

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}