vote up 1 vote down
star

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?

flag
add comment

4 Answers

vote up 7 vote down

Yes, using Array#sort! this is easy.

myarray.sort! { |a, b|  a.attribute <=> b.attribute }
link|flag
Thnx buddy but it didn't work out for me i 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 me can u help....?? – Satyam Gautam May 19 at 11:25
2 
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 May 20 at 13:19
add comment
vote up 4 vote down

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.

link|flag
add comment
vote up 2 vote down

I recommend using sort_by instead:

objects.sort_by {|obj| obj.attribute}

Especially if attribute may be calculated.

link|flag
add comment

Your Answer

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.