Sort a list of objects by using their attributes in Ruby

前端 未结 4 550
有刺的猬
有刺的猬 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条回答
  •  猫巷女王i
    2021-01-03 04:49

    See Array#sort (API doc). You can pass in a block that returns -1, 0, or 1 given two Fruit objects, and your block can determine these values using whatever attributes you please.

提交回复
热议问题