ruby和codewars中的类问题

时间:2016-04-05 20:52:02

标签: ruby

所以我在Codewars上尝试kata:灵活的纸牌游戏

http://www.codewars.com/kata/5436fdf34e3d6cb156000350/train/ruby

我写的代码已经通过了大多数测试,但最后绊倒了:

#draw
chooses cards from the end
Test Passed: Value == [[:clubs, 13]]

removes cards from the deck
Test Passed: Value == 51

returns the cards that were drawn
Test Passed: Value == 1

Expected [:clubs, 13] to be a Card
chooses cards from the end

Test Passed: Value == [[:clubs, 12], [:clubs, 13]]
removes cards from the deck

Test Passed: Value == 50
returns the cards that were drawn

Test Passed: Value == 2
Expected [:clubs, 12] to be a Card
Expected [:clubs, 13] to be a Card

我不明白的是,当测试调用方法绘制时,它似乎期望来自同一方法的不同返回。我确信这是我做错了但我看不到的。任何帮助都会很棒。这是我的代码:

class Card 
 include Comparable
 attr_accessor :suit, :rank
  def initialize(suit, rank)

      @suit = suit
      @rank = rank

  end

  def <=> (another_card)
    if self.rank < another_card.rank
         -1
    elsif self.rank > another_card.rank
          1
    else
          0
    end
  end

  def face_card?
    @rank > 10 ? true : false
  end

  def to_s
    @rank_hash = {13 => "King", 12 => "Queen", 11 => "Jack", 10 => "10", 9 => "9", 8 => "8", 7 => "7", 6 => "6", 5 => "5", 4 => "4", 3 => "3", 2 => "2", 1 => "Ace"}
    @suit_hash = {:clubs => "Clubs", :spades => "Spades", :hearts => "Hearts", :diamonds => "Diamonds"}
    "#{@rank_hash[@rank]} of #{@suit_hash[@suit]}"
  end

end

class Deck < Card
attr_accessor :cards
  def initialize

    @rank_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
    @suit_array = [:hearts, :diamonds, :spades, :clubs]
    @cards = @suit_array.product(@rank_array)

  end

  def count
    @cards.size
  end

  def shuffle
    @cards.shuffle!
  end

  def draw(n=1)
  @cards.pop(n)
  end

end

1 个答案:

答案 0 :(得分:0)

问题在于initialize方法。下面修正了这个问题。

def initialize
@cards = []
@rank_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
@suit_array = [:hearts, :diamonds, :spades, :clubs]
  @suit_array.each do |suit|
    @rank_array.each do |rank|
      each_card = Card.new(suit, rank)
      @cards << each_card
    end
  end
end