Sorting an array of objects in Ruby by object attribute?

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

    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
    
    0 讨论(0)
  • 2021-01-30 02:41
    @model_name.sort! { |a,b| a.attribute <=> b.attribute }
    
    0 讨论(0)
  • 2021-01-30 02:48

    Yes, using Array#sort! this is easy.

    myarray.sort! { |a, b|  a.attribute <=> b.attribute }
    
    0 讨论(0)
提交回复
热议问题