0

这是一个相当有名的。确定扑克手的等级。我创建了以下类Card

class Card
  attr_accessor :suite, :rank, :value
  def initialize(suite, rank, value)
    @suite = suite
    @rank = rank
    @value = value
  end
  def to_s
    puts "#{@value}, #{@suite}, #{@rank}"
  end
end

Deck

class Deck
  def initialize()
    @cardsInDeck = 52
    @deck = Array.new()
  end
  def add_card(card)
    @deck.push(card)
  end
  def deck_size
    @deck.length
  end
  def to_s
    @deck.each do |card|
      "#{card.rank}, #{card.suite}"
    end
  end
  def shuffle_cards
    @deck.shuffle!
  end
  def deal_cards
    #Here I create a new hand object, and when popping cards from the deck             
    # stack I insert the card into the hand. However, when I want to print 
    # the cards added to the hand I get the following error:
    #     : undefined method `each' for #<Hand:0x007fa51c02fd50> (NoMethodError)from   
    #       driver.rb:36:in `<main>'
    @hand = Hand.new
    for i in 0..51 do
      card = @deck.pop
      @cardsInDeck -= 1
      puts "#{card.value}, #{card.rank}, #{card.suite}"
      @hand.add_cards(card)
    end
    @hand.each do |index|
      "#{index.value}, #{index.rank}, #{index.suite}"
    end
    puts "Cards In Deck: #{@cardsInDeck}"
  end
end

Hand

require_relative 'deck'
require_relative 'card'

class Hand
  def initialize()
    @hand = Array.new()
  end
  def to_s
    count = 0
    @hand.each do |card|
      "#{card.value}, #{card.rank}, #{card.suite}"
      count += 1
    end
  end
  def add_cards(card)
    @hand.push(card)
  end
  def hand_size()
    @hand.length
  end
end

和驱动程序文件:

require 'logger'
require_relative 'card'
require_relative 'deck'
require_relative 'hand'

suite = ["Hearts", "Diamonds", "Clubs", "Spades"]
rank = ["Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"]
deck = Deck.new()
suite.each do |i|
  v = 1
  rank.each do |j|
    deck.add_card(Card.new(i, j, v))
    v += 1
  end
end

Deck类中,deal_card方法,我不明白为什么循环数组会导致方法错误

@hand.each do |index|
  "#{index.value}, #{index.rank}, #{index.suite}"
end
puts "Cards In Deck: #{@cardsInDeck}"
4

2 回答 2

0

我对错误的回答不是很直接,但希望在这种情况下对您有所帮助。

  1. 你的方法deal_cards依赖注入可以发挥作用的地方。原始设计对哪个不好且更难测试Deck有硬依赖。Hand你需要像这样改变它

    def deal_cards(hand=nil)
      @hand = hand || Hand.new
      # Others
    end
    

    这样你就可以接受外面的例子了Hand,说Foot只要有人会用脚打牌!您也可以在完全不编写 Hand 类的情况下对该方法进行单元测试。

  2. 最好对类进行单元测试而不是手动检查,然后您可以在测试期间将任何您喜欢的实例注入此方法。

于 2013-10-12T03:57:53.390 回答
0

@hand是 的一个实例Hand,并且没有为each定义实例方法Hand,所以这就是@hand.each产生undefined method错误的原因。

于 2013-10-12T02:06:49.207 回答