1

I am trying to figure out how to pass variables between classes in Ruby. The example I am working on now is a game, where the players health, equipment, etc keeps changing and is passed from scene to scene until the game is over. Here is what I have so far:

class Player
  def enter()
  end
end

class MyPlayer < Player
  def initialize()
    dog_biscuits = false
  end
end

class Scene
  def enter()
  end
end

class Entrance < Scene
  def enter(player)
    puts "You are in the entrance"
    if player.dog_biscuits == false
      puts "You don't have any biscuits."
    end
  end
end

player = MyPlayer.new
entrance = Entrance.new
entrance.enter(player)

Whenever I run this, I get the following error message:

entrance.rb:20:in `enter': undefined method `dog_biscuits' for #<MyPlayer:0x007fbfe2167f20> (NoMethodError)

I am running ruby 2.2.3p173 on OSX El Capitan.

2 Answers2

0

Do this:

class MyPlayer < Player
  attr_accessor :dog_biscuits
  def initialize()
    @dog_biscuits = false
  end
end

Using attr_accessor will allow you to set and get instance variables. Remember also that you have to prefix instance variables with @.

PatNowak
  • 5,721
  • 1
  • 25
  • 31
0
class MyPlayer < Player

  def initialize()
    @dog_biscuits = false
  end

  def has_no_dog_biscuits?
    @dog_biscuits == false
  end
end

It is better to create method has_no_dog_biscuits? then to have attr_reader and to expose attribute to outer world, this way, you can always check if player has not dog_biscuits.

Nermin
  • 6,118
  • 13
  • 23