Sort a list of objects by using their attributes in Ruby

前端 未结 4 556
有刺的猬
有刺的猬 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:27

    If you need to sort Fruits a lot, you should probably do a little more work up front and make your objects comparable.

    For this, you need to implment the Spaceship-Operator (<=>) and include Comparable.

    class Fruit
      attr_accessor :name, :color
    
      def <=>(other)
        # use Array#<=> to compare the attributes
        [self.name.downcase, self.color] <=> [other.name.downcase, other.color]
      end
    
      include Comparable
    end
    

    then you can simply do:

    list_of_fruits.sort
    

    Comparable also gives you many other methods (==, <, >) for free, so you can do things like if (apple < banana) (see the documentation for the Comparable Module for more info)

    <=>, is specified to return -1 if self is smaller than other, +1 if other is smaller and 0 if both objects are equal.

提交回复
热议问题