可以将超类的实例作为普通类的实例进行相互通信

时间:2012-11-28 22:02:27

标签: ruby inheritance

类的实例可以访问其他实例的方法,但是是否可以使用不同的方法为类的两个不同的子类执行此操作?或者访问的方法必须包含在超类中吗?

1 个答案:

答案 0 :(得分:0)

听起来你需要通过将Deck实例传递给各个Hand实例来跟踪你的关联。以下是基于您描述的场景的示例:

class Card
   attr_accessor :suit, :value

  def initialize(suit, value)
    @suit = suit
    @value = value
  end
end

class Deck
  SUITS = ["Spades", "Clubs", "Diamonds", "Hearts"]
  VALUES = [2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A"]
  HAND_SIZE = 5

  attr_accessor :cards

  def initialize
    shuffle
  end

  def shuffle
    @cards = []
    SUITS.each do |suit|
      VALUES.each do |value|
        @cards << Card.new(suit, value)
      end
    end
    @cards.shuffle!
  end

  def deal_hand
    shuffle if @cards.size < (HAND_SIZE + 1)
    hand = @cards[0...HAND_SIZE]
    @cards = @cards.drop(HAND_SIZE)
    hand
  end
end

class Player
  attr_accessor :deck
  attr_accessor :hand

  def initialize(deck)
    @deck = deck
  end

  def draw!
    @hand = @deck.deal_hand
  end
end

# initialize
the_deck = Deck.new
players = []
players << (player1 = Player.new(the_deck))
players << (player2 = Player.new(the_deck))
players << (player3 = Player.new(the_deck))
players << (player4 = Player.new(the_deck))

# draw
players.each do |player|
  player.draw!
end

# play
# ... 

希望这有帮助。