James Gray
8/14/2006 9:46:00 PM
On Aug 14, 2006, at 4:04 PM, Laurent Colloud wrote:
> Hi,
>
> Here my - strange - problem.
>
> To explain it, let's take the example of football. I construct an
> array
> of hashes of the results with team_id, total of pts, number of wins,
> number of draws and number of defeats such as:
>
> myArray = Array.new
> myArray << {:team_id=>1, :pts=>5, :w=>0, :d=>5, :l=>5}
> myArray << {:team_id=>2, :pts=>7, :w=>1, :d=>4, :l=>5}
> myArray << {:team_id=>3, :pts=>4, :w=>0, :d=>4, :l=>6}
> myArray << {:team_id=>4, :pts=>6, :w=>1, :d=>3, :l=>6}
> myArray << {:team_id=>5, :pts=>5, :w=>0, :d=>5, :l=>5}
> myArray << {:team_id=>6, :pts=>5, :w=>0, :d=>5, :l=>5}
> myArray << {:team_id=>8, :pts=>10, :w=>2, :d=>4, :l=>4}
> myArray << {:team_id=>9, :pts=>5, :w=>1, :d=>2, :l=>7}
> myArray << {:team_id=>10, :pts=>8, :w=>1, :d=>5, :l=>4}
> myArray << {:team_id=>11, :pts=>9, :w=>2, :d=>3, :l=>5}
> myArray << {:team_id=>12, :pts=>6, :w=>1, :d=>3, :l=>6}
> myArray << {:team_id=>13, :pts=>5, :w=>0, :d=>5, :l=>5}
>
> Now, from this array, I want to get the table.
> So what I want to do is to sort the array, first by total of pts,
> then
> by number of wins (if 2 teams have the same total of points I put
> first
> the team with more wins) and then by number of draws.
Does this do what you were after?
$ irb -r pp
>> pp myArray.sort_by { |team| [team[:pts], team[:w], team
[:d]] }.reverse
[{:l=>4, :team_id=>8, :pts=>10, :w=>2, :d=>4},
{:l=>5, :team_id=>11, :pts=>9, :w=>2, :d=>3},
{:l=>4, :team_id=>10, :pts=>8, :w=>1, :d=>5},
{:l=>5, :team_id=>2, :pts=>7, :w=>1, :d=>4},
{:l=>6, :team_id=>12, :pts=>6, :w=>1, :d=>3},
{:l=>6, :team_id=>4, :pts=>6, :w=>1, :d=>3},
{:l=>7, :team_id=>9, :pts=>5, :w=>1, :d=>2},
{:l=>5, :team_id=>13, :pts=>5, :w=>0, :d=>5},
{:l=>5, :team_id=>6, :pts=>5, :w=>0, :d=>5},
{:l=>5, :team_id=>5, :pts=>5, :w=>0, :d=>5},
{:l=>5, :team_id=>1, :pts=>5, :w=>0, :d=>5},
{:l=>6, :team_id=>3, :pts=>4, :w=>0, :d=>4}]
=> nil
Hope that helps.
James Edward Gray II