2013-10-07 35 views
-1

結果:Ruby排序 - 爲什麼rspec錯誤在「預期:[7,6,5,5,4,3,3]」看起來與「got:[7,6,5,5,4,3,3]」相同?

Failures: 

    1) An usual sorter sorts downwards by default 
    Failure/Error: [a,b,c,d,e,f,g].sort.should == [7,6,5,5,4,3,3] 
     expected: [7, 6, 5, 5, 4, 3, 3] 
      got: [7, 6, 5, 5, 4, 3, 3] (using ==) 
    # ./downsort_spec.rb:13:in `block (2 levels) in <top (required)>' 

Finished in 0.00077 seconds 

測試:

require_relative 'my_sorter.rb' 

describe "A usual sorter" do 
    it "sorts downwards by default" do 
    my_array= [3,5,7,5,3,6,4,2,5,6] 
    a=MySorter.new(3) 
    b=MySorter.new(5) 
    c=MySorter.new(7) 
    d=MySorter.new(5) 
    e=MySorter.new(3) 
    f=MySorter.new(6) 
    g=MySorter.new(4) 
    [a,b,c,d,e,f,g].sort.should == [7,6,5,5,4,3,3] 
    end 
end 

代碼:

class MySorter 
    include Comparable 
    attr_reader :value 

    def initialize(value) 
    @value = value 
    end 

    def <=> (other) 
    if value > other.value then 
     -1 
    elsif value < other.value then 
     1 
    else 
     0 
    end 
    end 

    def inspect 
    @value 
    end 

end 

我有現在一個非常簡單的排序,意圖將是一個比較複雜的一個,一旦我有這個工作(因此比較方法的細節)。

回答

1

您正在將一個MySorter對象數組與一個Fixnums數組進行比較。你需要改變這一點:

[a,b,c,d,e,f,g].sort.should == [7,6,5,5,4,3,3] 

[a,b,c,d,e,f,g].sort.map(&:value).should == [7,6,5,5,4,3,3] 
-1

你的問題來了,因爲你沒有在MySorter中重寫==。

您有一個MySorter對象數組,然後嘗試與fixnums數組進行比較,而您要比較的是MySorter對象的內容。

在MySorter定義

def == (other) 
    other == value 
    end 

,你的問題得到解決。我認爲默認的ruby ==運算符會比較對象id或類似的,這在你的vanilla情況下顯然會失敗,因爲MySorter不是Fixnum。

0

涉及MySorter值的數組轉換成Fixnum值的數組是擴大你<=>方法的能力,處理答案的替代Fixnum比較通過包括以下作爲所述塊中的第一個語句:

other = MySorter.new(other) if other.class == 'Fixnum' 

可能有更優雅/高效的機制來實現這一點,但你明白了。

相關問題