Ruby 超级类的实例可以像普通类的实例那样相互通信吗

Ruby 超级类的实例可以像普通类的实例那样相互通信吗,ruby,inheritance,Ruby,Inheritance,一个类的实例可以访问其他实例的方法,但是对于一个具有不同方法的类的两个不同子类,是否可以这样做?或者访问的方法必须包含在超类中吗?听起来您需要通过将Deck实例传递给各个Hand实例来跟踪您的关联。以下是基于您描述的场景的示例: class Card attr_accessor :suit, :value def initialize(suit, value) @suit = suit @value = value end end class Deck SU

一个类的实例可以访问其他实例的方法,但是对于一个具有不同方法的类的两个不同子类,是否可以这样做?或者访问的方法必须包含在超类中吗?

听起来您需要通过将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
# ... 
类卡
属性访问器:suit,:value
def初始化(套件、值)
@西装
@价值=价值
结束
结束
甲板
套装=[“黑桃”、“梅花”、“钻石”、“红心”]
数值=[2,3,4,5,6,7,8,9,10,“J”,“Q”,“K”,“A”]
手部尺寸=5
属性存取器:卡片
def初始化
洗牌
结束
def洗牌
@卡片=[]
各就各位|
值。每个do |值|

@你想构建什么样的卡片?好吧,我有一个提供get_hand方法的卡片组类,我有很多hand类实例,它们需要使用这个类实例来随机确定手的数量!我自己的方法造成了循环问题!确切地说,为什么需要为此使用子类?你最多需要牌组、手牌和牌类。最有可能的情况是,你可以用更少的数组或散列来填充剩下的。。。我想起了这篇文章…@andrewgrim我没有输入“英语语法”。它来自Cleanshooter的编辑。我修改后接受了它。编辑标题已自动继承。