ruby - 如何在 Ruby 类之间传递变量?

标签 ruby variables

我正在创建一个包含多个类的纸牌游戏。目前,我正在使用全局变量来保存 $shuffled_deck$players_hand$dealers_hand 变量,但我担心使用全局变量时(也许是不必要的)并且更愿意使用实例变量。

我一直在四处阅读,但没有什么是真正点击的。谁能帮我指出正确的方向?

使用实例变量我无法保存 @players_hand@dealers_hand 以便能够在其他类中使用它们。例如,我有来自 Player 类的 @players_hand。我让 Dealer 类抽一张牌,但我无法将那张 @players_hand 拉入 Dealer 类以将两者相加。

我当前的代码是:

class Blackjack

  def initialize
    @player = Player.new
    @dealer = Dealer.new
  end
end

class Dealer

  def initialize
    @deck = Deck.new
    $dealers_hand = 0
  end

  def hit_dealer
    @deck.hit_dealer
  end

  def hit_player
    @deck.hit_player
  end

  def draw_card
    @hit = $shuffled_deck
  end

  def shuffle
    @deck.suits
  end
end

class Player

  def initialize
    $players_hand = 0
  end   
end

class Deck

 def suits
   #code that shuffled the deck..
   $shuffled_deck = @shuffled_deck
 end

 def hit_player
   @hit = $shuffled_deck.pop
 end

 def hit_dealer
   @hit = $shuffled_deck.pop
 end

end

最佳答案

使用你的例子你可以这样做

class Blackjack
  attr_reader :player, :dealer

  def initialize
    @player = Player.new
    @dealer = Dealer.new
  end
end

class Dealer
  def dealers_hand #the long java way of a getter
    @dealers_hand
  end

  #and now the short ruby way
  attr_reader :dealers_hand #if you only need to read the attribute
  attr_writer :dealers_hand #if you only need to write the attribute
  attr_accessor: dealers_hand #if you need both

  def initialize
    @deck = Deck.new
    @dealers_hand = 5
  end

  def hit_dealer
    @deck.hit_dealer
  end

  def hit_player
    @deck.hit_player
  end

  def draw_card
    @hit = $shuffled_deck
  end

  def shuffle
    @deck.suits
  end
end

class Player
  attr_reader :players_hand
  def initialize
    @players_hand = 0
  end   
end

class Deck

 def suits
   attr_reader :shuffled_deck
   @shuffled_deck = @shuffled_deck
 end

 def hit_player
   @hit = $shuffled_deck.pop
 end

 def hit_dealer
   @hit = $shuffled_deck.pop
 end

end

game = Blackjack.new
p game.dealer.dealers_hand
game.dealer.dealers_hand = 4
p game.dealer.dealers_hand

关于ruby - 如何在 Ruby 类之间传递变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9399025/

相关文章:

ruby-on-rails - Rails 服务器无法在 Rubymine 中工作,但可以在终端中工作?

ruby - 我如何在 heroku 中连接我的 postgres 数据库?

大约 30 分钟后 PHP session 变量为空

performance - 一阶公式中变量的有效重命名

c++ - 如何在 C++ 中将变量用作函数?

javascript - js 变量到 css [剪辑路径图片库]

ruby-on-rails - 使用 Rails 在公共(public)文件夹中本地提供 1GB 文件

ruby-on-rails - Heroku -/usr/bin/env : ruby1. 9.1: 没有那个文件或目录

c++ - 如何声明一个引用变量在条件 block 之间持续存在?

sql - 基于 has_many 模型列的结果计数的 Rails 查询