重载 <=> 运算符 ruby​​?

Zub*_*air 1 ruby

我是 ruby​​ 新手,不知道是否可以在 ruby​​ 中完成。

我们可以在 ruby​​ 中为自定义类对象重载组合比较运算符 <=> 吗?

Paw*_*zak 5

当然可以!谷歌搜索 Ruby 的宇宙飞船运营商会有所帮助。

您需要包含Comparable模块,然后实现该方法。看一下覆盖的简单示例<=>http : //brettu.com/rails-daily-ruby-tips-121-spaceship-operator-example/

我将从文章中举一个例子:

class Country
  include Comparable

  attr_accessor :age

  def initialize(age)
    @age = age 
  end 

  def <=>(other_country)
    age <=> other_country.age
  end 
end
Run Code Online (Sandbox Code Playgroud)

对于重载,<=>您不需要包含Comparable模块,但是通过包含它,它会将一些有用的方法“混合”到您的Country类中,您可以使用这些方法进行比较。

让我们看一些例子:

country1 = Country.new(50)
country2 = Country.new(25)

country1 > country2
# => true

country1 == country2
# => false 

country1 < country2
# => false

country3 = Country.new(23)

[country1, country2, country3].sort
# => [country3, country2, country1]
Run Code Online (Sandbox Code Playgroud)

但是,如果Comparable不包含该模块:

country1 > country2
# => NoMethodError: undefined method `>' for #<Country:...>
Run Code Online (Sandbox Code Playgroud)

祝你好运!

  • 的确。关系是倒退的:你需要在包含 `Comparable` 时实现 `&lt;=&gt;`。 (3认同)