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! -- Posted via http://www.ruby-forum.com/. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---
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 -- Posted via http://www.ruby-forum.com/. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---
On Jan 29, 2009, at 7:33 PM, Scott Kulik wrote:> 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 helpActually, 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-xa9cJyRlE0mWcWVYNo9pwxS2lgjeYSpx@public.gmane.org --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---