Sorting an array of objects in Ruby by object attribute?

后端 未结 9 778
渐次进展
渐次进展 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:24

    I recommend using sort_by instead:

    objects.sort_by {|obj| obj.attribute}
    

    Especially if attribute may be calculated.

    Or a more concise approach:

    objects.sort_by(&:attribute)
    

提交回复
热议问题