Question

I have a hash with labeled numbered questions (the keys), and five possible answers (the values)

questions = {
  likert_1:  %w(choice_5mMP0CMR9tC choice_6kUil9z7wi4 choice_6ZQQ7c2KR3O choice_6ilb652FCqZ choice_6Z3NYElYPPM),
  likert_2:  %w(choice_5pjBFzoqqpc choice_6AARUgqxvGL choice_5lnoEM7GUYr choice_5inpB7UT9Bs choice_6N6ETdSVpFP)
}

The database is saving per user, one value per question. So the database could have any combination of one value per each likert_# . But! the database will not save them in the order they were answered.

Therefore, I am trying to find an elegant way to sort any given two responses by how they are ordered likert_1 before likert_2

So if I had : [choice_5pjBFzoqqpc choice_5mMP0CMR9tC] . Then they should be returned reversed as : [choice_5mMP0CMR9tC, choice_5pjBFzoqqpc] because choice_5mMP0CMR9tC appears in likert_1 and choice_5pjBFzoqqpc appears in likert_2.

Was it helpful?

Solution

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"]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top