Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Ruby/RoR-根据关联数组循环对象数组_Ruby On Rails_Ruby_Loops - Fatal编程技术网

Ruby on rails Ruby/RoR-根据关联数组循环对象数组

Ruby on rails Ruby/RoR-根据关联数组循环对象数组,ruby-on-rails,ruby,loops,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:Quest

我有一系列问题的对象@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"
和一系列答案@答案

--- !map:ActiveSupport::HashWithIndifferentAccess 
"1": "2"
"7": "3"
"6": "4"
"4": "0"
如何使用任何循环机制验证问题的答案

在上面的例子中,只有第一个问题的答案是正确的,我需要像下面这样以数组的形式输出

--- !map:ActiveSupport::HashWithIndifferentAccess 
"1": true
"7": false
"6": false
"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}