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.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Tom Hammond
  • 5,842
  • 12
  • 52
  • 95

1 Answers1

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

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Raj
  • 22,346
  • 14
  • 99
  • 142