Mithun Sreedharan
Mithun Sreedharan

Reputation: 51264

Ruby/ RoR - Looping array of objects against an associative array

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

Upvotes: 0

Views: 398

Answers (1)

Mladen Jablanović
Mladen Jablanović

Reputation: 44080

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}

Upvotes: 1

Related Questions