Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass variables between Ruby classes?

Tags:

variables

ruby

I'm creating a card game with multiple classes. Currently, I'm using global variables to hold the $shuffled_deck, $players_hand, and $dealers_hand variables, but I worry when using global variables (perhaps, needlessly) and would prefer to use instance variables.

I've been reading around, but nothing is really clicking. Can anyone help point me in the right direction with this?

Using instance variables I haven't been able to save the @players_hand and @dealers_hand to be able to use them in other classes. For instance, I have @players_hand from the Player class. I have the Dealer class draw a card, but I can't pull that @players_hand into the Dealer class to add the two together.

My current code is:

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
like image 481
Alekx Avatar asked Feb 22 '12 16:02

Alekx


1 Answers

using your example you can do it like this

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
like image 115
peter Avatar answered Nov 01 '22 19:11

peter