As I also pointed out as a comment, it is probably much more efficient and more elegant to do the ordering in the query that retrieves the answers instead of afterwards. Since you have Answer
and (presumably) Question
tables, and a relationship between Answer
and Question
you can just order on your desired Question
attribute in the query using an ORDER BY.
Having said that; since you asked about ordering the Array
containing answers based on the order of the questions in the provided Hash
and nobody answered yet, I will answer that question.
The simple idea here is to find the index of the question that contains the answer as one of its choices and use that index as the sort_by
attribute. You can do that in the following way:
answers = ["choice_5pjBFzoqqpc", "choice_5mMP0CMR9tC"]
question_choices = questions.values
sorted = answers.sort_by { |a| question_choices.find_index { |c| c.include? a } }
# ["choice_5mMP0CMR9tC", "choice_5pjBFzoqqpc"]