views:

1212

answers:

4

Hi,

I have an array of objects in ruby on rails. I want to sort this array by an attribute of the object. Is it possible?

+10  A: 

Yes, using Array#sort! this is easy.

myarray.sort! { |a, b|  a.attribute <=> b.attribute }
Konrad Rudolph
Thnx buddybut it didn't work out for mei have an array of objects. In which one of the attribute of the object is created_at.I want to sort it with this field. so i did @comm_bytes.sort! {|a, b| a.created_at <=> b.created_at }but no luck for mecan u help....??
Is there a created_at method to access the @created_at attribute? What kind of object is @created_at? Does it define `<=>`? What kind of errors are you getting? etc, etc, ad nauseum. In other words, we need more detail than "but no luck for me".
rampion
+5  A: 

Array#sort works well, as posted above:

myarray.sort! { |a, b|  a.attribute <=> b.attribute }

BUT, you need to make sure that the <=> operator is implemented for that attribute. If it's a Ruby native data type, this isn't a problem. Otherwise, write you own implementation that returns -1 if a < b, 0 if they are equal, and 1 if a > b.

Curt Sampson
+5  A: 

I recommend using sort_by instead:

objects.sort_by {|obj| obj.attribute}

Especially if attribute may be calculated.

Scott