Re: sorting an array based on two attributes of objects

Rob Biedenharn
Mon, 26 Mar 2007 13:24:53 -0000

On Mar 26, 2007, at 8:50 AM, senthil wrote:
> Hi all,
>      I want to sort the objects of array based on two attributes.I
> want
> sort an employee class based on his salary and name , so that if two
> person has same salary it should be sorted with name.
>      Lets say for example the employee objects has following name and
> salary.
>
>          name      salary
>            d        100
>            c        200
>            b        50
>            a        100
>
>
>      so in this case the result which i expect is
>
>          name      salary
>            c        50
>            a        100
>            d        100
>            b        200
>
>   Note:In the above example for salary 100 the sorting is done
> alphabetically, but initially(before sorting) ''d'' came
first and then
> ''a'' came.so basically i want to sort the array with more
than one
> order.
>   Can any one help me to solve it ??

[ [''d'',100], [''c'',200],
[''b'',50], [''a'',100] ].sort_by {|ns|
[ ns.last, ns.first ]}
=> [["b", 50], ["a", 100], ["d", 100],
["c", 200]]

An array compares on its elements.

-Rob

Rob Biedenharn		http://agileconsultingllc.com
Rob-xa9cJyRlE0mWcWVYNo9pwxS2lgjeYSpx@public.gmane.org