Forum: Ruby sorting an array basedon 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 16:48
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 ??
MenTaLguY (Guest)
on 2007-03-26 16:54
(Received via mailing list)
On Mon, 26 Mar 2007 21:48:17 +0900, senthil
<removed_email_address@domain.invalid> wrote:
>      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.

Is this what you had in mind?

 sorted_employees = employees.sort_by { |e| [ e.salary, e.name ] }

-mental
Augie De Blieck Jr. (Guest)
on 2007-03-26 16:55
(Received via mailing list)
I think you could try this:

results = person.sort_by { |p| [p.salary, p.name] }

That should sort by salary first, then name.

-Augie
Florian Groß (Guest)
on 2007-03-26 16:57
(Received via mailing list)
On 26 Mrz., 14:48, senthil <removed_email_address@domain.invalid> wrote:

>      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.

Try this: employees.sort_by { |employee| [employee.salary,
employee.name] }

Kind regards,
Florian G.
This topic is locked and can not be replied to.