From: "David A. Black" Date: 2009-08-31T00:41:17+09:00 Subject: Re: Sorting an array by multiple elements? Hi -- On Mon, 31 Aug 2009, Paul Carvalho wrote: > Thanks for the great feedback! I couldn't find good documentation for > the 'sort_by' and the examples provided didn't work with my data. It > did nothing actually, which surprised me. Josh and Stefano's approach > worked well enough. The nothing result seems strange. This: data = [ [3, "2009-08-23", 3, "alfie"], [5, "2009-08-24", 1, "cliff"], [6, "2009-08-23", 3, "alfie"], [1, "2009-08-21", 4, "barny"], [2, "2009-08-21", 2, "alfie"] ] data.sort_by {|id, date, num, name| [name, date, id] } gives me: [ [2, "2009-08-21", 2, "alfie"], [3, "2009-08-23", 3, "alfie"], [6, "2009-08-23", 3, "alfie"], [1, "2009-08-21", 4, "barny"], [5, "2009-08-24", 1, "cliff"]] For documentation: ri Enumerable#sort_by > Unfortunately, the data in the array is not a fixed size. Sometimes > it is [ id, date, num, name ] and sometimes it may be [ id, date, num, > name1, name2 ] (or more names.. I don't know how many since the data > collection script figures it out as it goes along). > > When I do the sort by 'name' (e.g. first = a_name <=> b_name ), all > the records with _additional_ names appears at the bottom of the list > as if it were a different name (unexpected). > > For example, the output (now) looks like: > > [2, "2009-08-21", 2, "alfie"] > [3, "2009-08-23", 3, "alfie"] > [6, "2009-08-23", 3, "alfie"] > [1, "2009-08-21", 4, "barny"] > [5, "2009-08-24", 1, "cliff"] > [4, "2009-08-21", 1, "cliff", "bob"] > > .. but I expect/want the output to look like: > [2, "2009-08-21", 2, "alfie"] > [3, "2009-08-23", 3, "alfie"] > [6, "2009-08-23", 3, "alfie"] > [1, "2009-08-21", 4, "barny"] > [4, "2009-08-21", 1, "cliff", "bob"] > [5, "2009-08-24", 1, "cliff"] > > > Any thoughts? Yeah -- sort_by :-) data = [ [2, "2009-08-21", 2, "alfie"], [6, "2009-08-23", 3, "alfie"], [1, "2009-08-21", 4, "barny"], [3, "2009-08-23", 3, "alfie"], [5, "2009-08-24", 1, "cliff"], [4, "2009-08-21", 1, "cliff", "bob"] ] data.sort_by {|id, date, num, name| [name, date, id] } gives me: [2, "2009-08-21", 2, "alfie"] [3, "2009-08-23", 3, "alfie"] [6, "2009-08-23", 3, "alfie"] [1, "2009-08-21", 4, "barny"] [4, "2009-08-21", 1, "cliff", "bob"] [5, "2009-08-24", 1, "cliff"] David -- David A. Black / Ruby Power and Light, LLC / http://www.rubypal.com Ruby/Rails training, mentoring, consulting, code-review Latest book: The Well-Grounded Rubyist (http://www.manning.com/black2) September Ruby training in NJ has been POSTPONED. Details to follow.