Rails Transform_Values Just One Key[Value]
I've Got Below Hash of Hashes Answers = {"0"=>{"Id"=>"1", "Answer"=>"0" }, "1"=>{"Id"=>"2", "Answer"=>"0" }, "2"=>{"Id"=>"10", "Answer"=>"0" }...
I've got below hash of hashes
answers = {"0"=>{"id"=>"1", "answer"=>"0" },
"1"=>{"id"=>"2", "answer"=>"0" },
"2"=>{"id"=>"10", "answer"=>"0" },
"3"=>{"id"=>"11", "answer"=>"0" },
"4"=>{"id"=>"12", "answer"=>"0" },
"5"=>{"id"=>"13", "answer"=>"0" },
"6"=>{"id"=>"7", "answer"=>"0" }}
Now I want to replace 'answer' value to real answer. To do so I could use below map:
correct_answers = answers.map { |key, value| AppropriatenessTestQuestion.find(value['id']).answers[value['answers'].to_i] }
=> ["Yes", "No", "Don't know", "Yes", "Yes", "No", "Yes"]
But how to replace the hash value of the key answer by '<correct_answers>' in the same order to have a expected hash as given below:
answers = {"0"=>{"id"=>"1", "answer"=>"Yes"},
"1"=>{"id"=>"2", "answer"=>"No"},
"2"=>{"id"=>"10", "answer"=>"Don't know"},
"3"=>{"id"=>"11", "answer"=>"Yes"},
"4"=>{"id"=>"12", "answer"=>"Yes"},
"5"=>{"id"=>"13", "answer"=>"No"},
"6"=>{"id"=>"7", "answer"=>"Yes"}}
I was trying to use transform_values:
answers.transform_values { |value| AppropriatenessTestQuestion.find(value['id']).answers[value['answers'].to_i] }
But instead of the whole hash I only get the following:
=> {"0"=>"Yes", "1"=>"Yes", "2"=>"Yes", "3"=>"Yes", "4"=>"Yes", "5"=>"Yes", "6"=>"Yes"}
1 Answer
something like this will replace:
"answer"=>"0" with "answer"=>"Yes" and return updated answers hash
answers.each do |_, value|
value['answer'] = AppropriatenessTestQuestion
.find(value['id'])
.answers[value['answers'].to_i]
end