按对象属性对Ruby中的对象数组进行排序? [英] Sorting an array of objects in Ruby by object attribute?
本文介绍了按对象属性对Ruby中的对象数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Ruby on Rails中有一个对象数组.我想按对象的属性对数组进行排序.有可能吗?
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?
推荐答案
我建议改用sort_by:
I recommend using sort_by instead:
objects.sort_by {|obj| obj.attribute}
尤其是可以计算属性的情况.
Especially if attribute may be calculated.
或更简洁的方法:
objects.sort_by(&:attribute)
这篇关于按对象属性对Ruby中的对象数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文