在 Ruby 中使用 spaceship 运算符按 2 个属性对数组中的对象进行排序

Huy*_*ran 1 ruby arrays sorting object spaceship-operator

我有一个SizeMatters类,它从给定的字符串创建一个对象。为了对数组中的这些对象进行排序,我实现了该<=>(other)方法。但以下代码仅帮助对象按大小排序。我还希望数组按字母顺序排序。

class SizeMatters
  include Comparable
  attr :str
  def <=>(other)
    str.size <=> other.str.size
  end
  def initialize(str)
    @str = str
  end
  def inspect
    @str
  end
end

s1 = SizeMatters.new("Z")
s2 = SizeMatters.new("YY")
s3 = SizeMatters.new("xXX")
s4 = SizeMatters.new("aaa")
s5 = SizeMatters.new("bbb")
s6 = SizeMatters.new("WWWW")
s7 = SizeMatters.new("VVVVV")

[ s3, s2, s5, s4, s1 , s6, s7].sort #[Z, YY, bbb, xXX, aaa, WWWW, VVVVV]
Run Code Online (Sandbox Code Playgroud)

我想要的是这个

[ s3, s2, s5, s4, s1 , s6, s7].sort #[Z, YY, aaa, bbb, xXX, WWWW, VVVVV]
Run Code Online (Sandbox Code Playgroud)

如何编写才能<=>(other)使数组中的对象首先按大小排序,然后按字母顺序排序?

ste*_*lag 6

定义<=>如下:

   def <=>(other)
     [str.size, str] <=> [other.str.size, other.str]
   end
Run Code Online (Sandbox Code Playgroud)