当然可以!谷歌搜索 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)
祝你好运!
| 归档时间: |
|
| 查看次数: |
184 次 |
| 最近记录: |