I have an array of objects in Ruby on Rails. I want to sort the array by an attribute of the object. Is it possible?
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.