ruby sort_by twice

后端 未结 3 592
忘了有多久
忘了有多久 2020-12-16 01:28

Ruby has a sort_by method on Enumerables. Fantastic! So you can do something like

entries.sort_by { |l| l.project.name }

That would sort

相关标签:
3条回答
  • 2020-12-16 01:50

    Return an array:

    entries.sort_by { |l| [ l.project.name, l.project.time] }
    

    this works because the <=> operator on arrays does a field-by-field 'lexical' comparison which is what you're looking for.

    0 讨论(0)
  • 2020-12-16 01:53

    I would suggest putting the column you want to sort by into an array.

    entries.sort_by { |l| [l.project.name, l.project.time] }
    

    This will respect the natural sort order for each type.

    0 讨论(0)
  • 2020-12-16 02:04

    You can use the regular sort method to do it.

    entries.sort do |a, b|
      comp = a.project.name <=> b.project.name
      comp.zero? ? (a.project.time <=> b.project.time) : comp
    end
    
    0 讨论(0)
提交回复
热议问题