【问题标题】:Comparing items based on their index in an array in Ruby根据 Ruby 数组中的索引比较项目
【发布时间】:2010-03-05 01:00:11
【问题描述】:

我有一个Card 类,我想重载> 运算符以与另一张牌进行比较(Ace 高于 King,K 高于 Queen,等等)。我已经忘记了我对 Ruby 的了解很少,也不知道从哪里开始。

class Card
  @@RANKS = ['A', 'K', 'Q', 'J', 'T', '9', '8','7','6','5','4','3','2']
  attr_reader :rank

  def initialize(str)
    @rank = str[0,1]
  end

  def > (other)
    #?????
  end
end

【问题讨论】:

    标签: ruby arrays compare


    【解决方案1】:

    如果你定义了宇宙飞船运算符而不是大于,你可能会更开心。 ()

    例如,排序取决于它的定义。

    http://ruby-doc.org/ruby-1.9/classes/Enumerable.html

    【讨论】:

    • 是否会实现 隐式实现 > 也?
    • 啊,需要 'include Comparable'
    【解决方案2】:

    我同意达林特。

    您需要做的就是包含 Comparable 并定义 ,然后您就可以免费进行所有其他比较!为您提供更多的灵活性,而不仅仅是自己定义“>”。

    用镐书的话来说: “Comparable mixin 可用于将比较运算符(= 和 >)以及 between? 方法添加到类中。为此,Comparable 假定任何类使用它的定义了运算符 。因此,作为类编写者,您可以定义一个方法 ,包含 Comparable,并免费获得六个比较函数。”

    (免费在线)镐书中提供了完整示例: http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html#S2 (向下滚动几段到“Mixins 为您提供了一种非常可控的方式..”)

    【讨论】:

      【解决方案3】:

      您可以使用array.index 方法。以下代码检查两张卡片的索引,如果 other 卡片出现在当前卡片之后,则返回 true

      class Card
        @@RANKS = ['A', 'K', 'Q', 'J', 'T', '9', '8','7','6','5','4','3','2']
        attr_reader :rank
      
        def initialize(str)
          @rank = str[0,1]
        end
      
        def > (other)
          @@RANKS.index(other.rank) > @@RANKS.index(@rank)
        end
      end
      
      ace = Card.new 'A'
      king = Card.new 'K'
      nine = Card.new '9'
      
      puts ace > king
      puts ace > nine
      puts nine > king
      

      【讨论】:

        猜你喜欢
        • 2020-12-07
        • 2016-03-26
        • 2021-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-07
        • 1970-01-01
        相关资源
        最近更新 更多