加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 23:30:59 所属栏目:百科 来源:网络整理
导读:我正在创建一个包含多个班级的纸牌游戏.目前,我使用全局变量来保存$shuffled_deck,$players_hand和$dealers_hand变量,但我担心使用全局变量(可能是,不必要)并且更喜欢使用实例变量. 我一直在看书,但没有什么是真的点击.任何人都可以帮我指出正确的方向吗?
我正在创建一个包含多个班级的纸牌游戏.目前,我使用全局变量来保存$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

解决方法

您想使用attr_reader,attr_writer或attr_accessor.以下是它们的工作原理:

> attr_reader:players_hand:允许你编写some_player.players_hand来获取该玩家的players_hand实例变量的值
> attr_writer:players_hand:允许你编写some_player.players_hand = 0来将变量设置为0
> attr_accessor:players_hand:允许您同时读写,就好像您同时使用了attr_reader和attr_writer一样.

顺便说一句,所有这些都是为您编写的方法.如果你想,你可以像这样手动完成:

class Player
  def initialize
    @players_hand = 0
  end  

  def players_hand
    @players_hand
  end

  def players_hand=(new_value)
    @players_hand = new_value
  end
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读