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
  • 413,090
  • 67
  • 810
  • 771
Tom Hammond
  • 5,320
  • 10
  • 47
  • 85

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

Lenin Raj Rajasekaran
  • 21,611
  • 14
  • 96
  • 136