0

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

1 Answer 1

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}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.