0

As the title states, I would like to do a sort_by such that my Course model can be sorted by its "year" column, but in such an order that I can specify.

Possible years are:

Freshman
Sophomore
Junior
Senior

So I'd like to make those into an array:

array_of_years = ["Freshman", "Sophomore", "Junior", "Senior"]

And sort my Courses by their year, in the order of that array.

For instance (pseudocode follows, I just made up the syntax to explain what I'm asking for):

Course.all.sort_by{ |course| course.year, array_of_years }

This would sort them in order of the array_of_years array, by ordering all Courses with a "year" column of "Freshman" first, and "Senior" last.

And if I wanted them sorted from Senior to Freshman, then I'd do:

Course.all.sort_by{ |course| course.year, array_of_years.reverse }

Or I could simply rearrange the array_of_years array to my liking and use the first block of code.

Is there a way to sort like this in Ruby/Rails?

1 Answer 1

3
Course.all.sort_by { |course| array_of_years.index(course.year) }

Reverse:

Course.all.sort_by { |course| -array_of_years.index(course.year) }
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.