sorting an array by mutliple fields

I can do sorting by a single field like the following:

@users.sort! { |a,b| a.name.downcase < => b.name.downcase }

but what if i want to sort by user.name and then user.rank?

what's the best way to do this?

thanks!

Scott Kulik wrote:

I can do sorting by a single field like the following:

@users.sort! { |a,b| a.name.downcase < => b.name.downcase }

but what if i want to sort by user.name and then user.rank?

what's the best way to do this?

thanks!

just got it:

@objects.sort! do |a,b|   comp = (b.rank <=> a.rank)   comp.zero? ? (b.position <=> a.position) : comp end

in case anyone else needs help

Actually, you can simplify that a bit:

@objects.sort! do |a,b|    (b.rank <=> a.rank).nonzero? || b.position <=> a.position end

Look at the docs for Numeric#nonzero?

-Rob

Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com