红宝石排序 - 为什么 rspec 错误"expected: [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

我现在有一个非常简单的排序,一旦我有了这个工作,意图就会更加复杂(因此比较方法中的细节)。

您正在将 MySorter 对象数组与 Fixnum 数组进行比较。您需要更改此设置:

[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]

涉及将MySorter值数组转换为Fixnum值数组的答案的替代方法是通过将以下内容作为块中的第一个语句来扩展 <=> 方法处理Fixnum比较的功能:

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

可能有更优雅/有效的机制来实现这一点,但你明白了。

你的问题出现了,因为你没有在MySorter中覆盖==。

您有一个 MySorter 对象数组,然后尝试将其与 fixnum 数组进行比较,而您要比较的是 MySorter 对象的内容。

定义

  def == (other)
    other == value
  end

在"我的分类器"中,您的问题已解决。 我认为默认的 ruby == 运算符比较对象 ID 或类似内容,这在您的原版情况下显然会失败,因为 MySorter 不是 Fixnum。

相关内容

最新更新