2010-12-20 29 views
0

我h've的對象的數組問題@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" 

和解答的Array @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} 
數組