2015-03-02 109 views
0

我是新来的红宝石,不知道它是否可以在红宝石。超载<=>运算符ruby?

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

回答

4

当然可以!这对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 

对于超载<=>你并不需要通过包括它包括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] 

但是,如果没有包括Comparable模块:

country1 > country2 
# => NoMethodError: undefined method `>' for #<Country:...> 

祝你好运!

+1

你可以实现'<=>'而不包括'Comparable' – Stefan 2015-03-02 11:27:39

+3

的确。这种关系是倒退的:当包含“Comparable”时,你需要实现'<=>'。 – 2015-03-02 11:29:34

+0

谢谢澄清!没有包括'可比较的'没有尝试,但我会! – 2015-03-02 11:58:08