2015-03-02 106 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