0

Let's say I have an array called surveys that's made up of Survey.all

Each survey model has a length and cost columns.

What's the best way to sort an array first on length, and then on cost.

I basically want to do something similar to Survey.all.order(length: :desc, cost: :asc) but on the array after it's created.

2

1 Answer 1

3

Use sort_by:

surveys.sort_by { |survey| [survey.length, survey.cost] }

If you want to control asc vs desc, just multiply by -1:

surveys.sort_by { |survey| [-1 * survey.length, survey.cost] }

This should work for both regular array of objects or ActiveRecord::Relation

Sign up to request clarification or add additional context in comments.

3 Comments

will that work just on the surveys array? At this point in time I will just have access to the array rather than the Survey.all (i.e. I'm not actually using Survey.all to get my array of surveys but it was easier to type)
should work, try and let me know
can also use -survey.length for desc.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.