Sha256: 741eb846ab9b00a4c382f35a97cea2f195845833f73f91e53eda17fee2b40fa5

Contents?: true

Size: 1.21 KB

Versions: 2

Compression:

Stored size: 1.21 KB

Contents

module Bridge
  class Card
    include Comparable

    attr_reader :card

    # Creates a new card
    def initialize(card)
      @card = card.to_s.upcase
      raise ArgumentError, "invalid card: #{card}" unless Bridge.card?(@card)
    end

    # Returns the suit of the card
    def suit
      card[0]
    end

    # Returns the suit of the card
    def value
      card[1]
    end

    # Returns the honour card points
    def honour_card_points
      (%w(J Q K A).index(value) || -1) + 1
    end
    alias :hcp :honour_card_points

    # Compares the card with the other card
    def <=>(other)
      case other
      when Card
        raise ArgumentError, "comparing card of suit #{suit} with suit #{other.suit}" unless suit == other.suit
        Bridge.compare_cards(self.card, other.card)
      when String
        self <=> Card.new(other)
      else
        begin
          a, b = other.coerce(self)
          a <=> b
        rescue
        end
      end
    end

    def eql?(other)
      self == other && other.instance_of?(Card)
    end

    def hash
      card.hash
    end

    def coerce(other)
      [Card.new(other.to_s), self]
    end

    def inspect
      card.inspect
    end

    def to_s
      card
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
bridge-0.2.0 lib/bridge/card.rb
bridge-0.0.13 lib/bridge/card.rb