如何通过include将类与任何其他任意类进行比较?方法

时间:2013-04-04 08:58:44

标签: ruby include comparable enumerable

我已经实现了可比较和可枚举,以便我可以使用比较并包括:

鉴于以下简单的课程:

class Card
  include Comparable
  include Enumerable
  attr_accessor :value

  def initialize(v)
    @value = v
  end

  def <=>(other)
    @value <=> other.value
  end

  def each
    yield @value
  end
end

然后:

c = Card.new(1) #so right now we have @value at 1

这些方法都不包括:

[1,3,4,5].include?(c)
c.include?([1,3,4,5])

是否可以使用include方法来执行此操作?我知道我可以用另一种方式做到这一点,但我想这样做“像红宝石一样”! (假设这甚至像红宝石一样......)我只是从java和c ++进入ruby

提前致谢!

1 个答案:

答案 0 :(得分:1)

如果你长时间盯着你的代码,你会看到。您实施了一个假设otherCard的太空船运营商。但是你在Fixnums上调用它!你需要在那里进行一些类型检查:

class Card
  include Comparable
  include Enumerable

  attr_accessor :value
  def initialize(v)
    @value = v
  end
  def <=>(other)
    if other.is_a?(Card)
      @value <=> other.value
    else
      @value <=> other
    end
  end

  def each
    yield @value
  end
end

c = Card.new(1)

[1,3,4,5].include?(c) # => true
c.include?([1,3,4,5]) # => false # because 1 does not contain an array [1, 2, 3, 4, 5]