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?
Ascending order :
objects_array.sort! { |a, b| a.attribute <=> b.attribute }
or
objects_array.sort_by{ |obj| obj.attribute }
Descending order :
objects_array.sort! { |a, b| b.attribute <=> a.attribute }
or
objects_array.sort_by{ |obj| obj.attribute }.reverse
@model_name.sort! { |a,b| a.attribute <=> b.attribute }
Yes, using Array#sort! this is easy.
myarray.sort! { |a, b| a.attribute <=> b.attribute }