Sorting an array of objects in Ruby by object attribute?

后端 未结 9 787
渐次进展
渐次进展 2021-01-30 02:00

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?

9条回答
  •  不要未来只要你来
    2021-01-30 02:27

    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.

提交回复
热议问题