Sorting an array of objects in Ruby by object attribute?

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

    in case you need sorting by two attributes, where first one is more important then second (means taking in account second arguments only if first arguments are equal), then you may do like this

    myarray.sort{ |a,b| (a.attr1 == b.attr1) ? a.attr2 <=> b.attr2 : a.attr1 <=> b.attr1 }
    

    or in case of array of arrays

    myarray.sort{ |a,b| (a[0] == b[0]) ? a[1] <=> b[1] : a[0] <=> b[0] }
    

提交回复
热议问题