2010-12-20 9 views
0

は私がのオブジェクトの配列をh've質問@questionsルビー/ RoRの - 連想配列に対してオブジェクトの配列をループ

--- 
- !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
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} 
以下のような配列として配置する必要があります