Sort a list of objects by using their attributes in Ruby

前端 未结 4 521
有刺的猬
有刺的猬 2021-01-03 04:11

I have a list of Fruit structs called basket. Each Fruit struct has a name (a string) and a calories (an int

4条回答
  •  隐瞒了意图╮
    2021-01-03 04:29

    The easy solution is

    basket.sort_by { |f| [-f.calories, f.name] }
    

    Of course, if this is the canonical sort order for fruit then it should be defined using the <=> method and with the Comparable module mixed into Fruit

提交回复
热议问题