squiggs77-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org
2007-Nov-27 20:11 UTC
Need to Sort Array of Hashes using multiple keys.
I have an array of hashes that makes up a table that isn''t associated with a Model. Each Hash is a represents a column. For instance the Array would be setup as follows: rows << {:name => row_name, :status => row_status, :date => row_date } If I needed to sort by ":name" then ":date" then ":status". How would I do that? Thanks --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---
squiggs77-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org
2007-Nov-27 22:02 UTC
Re: Need to Sort Array of Hashes using multiple keys.
I figured it out: Sort by 1 Column: sorted_rows = rows.sort { |a,b| a[col_1] <=> b[col_1] } Sort by 2 Columns: sorted_rows = rows.sort { |a,b| a[col_1] == b[col_1]? a[col_2] <=> b[col_2] : a[col_1] <=> b[col_1] } Sort by 3 Columns: sorted_rows = rows.sort { |a,b| a[col_1] == b[col_1]? ( a[col_2] =b[col_2]? a[col_3] <=> b[col_3] : a[col_2] <=> b[col_2] ) : b[col_1] <=> a[col_1] } Where ''col_1'' ''col_2'' and ''col_3'' are the hash keys that represent the columns. --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---