Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array of objects by an attribute of the objects?

I'm performing this query in a controler and the 'Group' model has_many Users

@group= Group.find(params[:id]) 

@group is being used to render this partial (the partial dumps the users of a group into a table)

<%= render :partial=>"user_list", :locals=>{:users=>@group.users} %> 

The local variable 'users' passed to the partial is an array of User objects;

- !ruby/object:User    attributes:      updated_at: 2011-01-04 21:12:04     firstname:  Bob     lastname: Smith     id: "15"     group_id: "2"     created_at: 2010-11-26 12:54:45 

How can the user array be sorted by 'lastname'? I've tried several different ways without any luck. Trying to sort by a object attribute inside an array in confusing me. Also, I don't undertand how I could do this with an :order in the query (how to :order not the Group but the Users of each group)?

Maybe I'm not referring to name of the object correctly ('User')? It seems like this should work be it produces a 'no method' error (or a dynamic constant assignment error if 'sort_by' is used without the !):

 users.sort_by! {|User| User.lastname} 

Thanks for any help.

like image 426
Reno Avatar asked Jan 06 '11 00:01

Reno


People also ask

How do you sort a list of objects based on an attribute of the objects?

sort() function to sort a collection of objects (using some attribute) in Python. This function sorts the list in-place and produces a stable sort. It accepts two optional keyword-only arguments: key and reverse. The key argument specifies a single-arg function to extract a comparison key from each list object.

How do you sort a list of objects based on an attribute of the objects in JavaScript?

In JavaScript, we use the sort() function to sort an array of objects. The sort() function is used to sort the elements of an array alphabetically and not numerically. To get the items in reverse order, we may use the reverse() method.

How do you sort an array by object value?

To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.


1 Answers

I found a method that works from here. I don't understand what the "&" symbol is doing - maybe it's shorthad for "object" since in my case ":lastname" is an attribute of the object that make up the array.

users = users.sort_by &:lastname 

note: I don't undertand why but a destructive version won't work. It produces a "undefined method `sort_by!' for #" errror:

users.sort_by! &:lastname 
like image 198
Reno Avatar answered Oct 22 '22 13:10

Reno