sorting an array basedon two attributes of objects

S

senthil

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 ??
 
F

Florian Groß

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 Gross
 
M

MenTaLguY

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
 
A

Augie De Blieck Jr.

I think you could try this:

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

That should sort by salary first, then name.

-Augie
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top