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?
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?
Yes, using Array#sort!
this is easy.
myarray.sort! { |a, b| a.attribute <=> b.attribute }
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.
I recommend using sort_by instead:
objects.sort_by {|obj| obj.attribute}
Especially if attribute may be calculated.