Forum: Ruby on Rails sorting an array based on two attributes of objects

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
senthil (Guest)
on 2007-03-26 17:57
Thanks for some of your replies for the lst post i need small
modification in that post .. i want to sort the salary in descending
order. i have explained the same quesion again....

Hi all,
     I want to sort the objects of array based on two attributes.I want
sort an employee class based on his salary in descecding order 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
           b        200
           a        100
           d        100
           c        50

  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 ??
Rob B. (Guest)
on 2007-03-26 19:01
(Received via mailing list)
On Mar 26, 2007, at 9:57 AM, senthil wrote:
> person has same salary it should be sorted with name.
>      so in this case the result which i expect is
> 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.  (The only change from my earlier
response is to negate the salary for sorting purposes.)

-Rob

Rob B.    http://agileconsultingllc.com
removed_email_address@domain.invalid
This topic is locked and can not be replied to.