Understanding accessing class variables in multiple files

#1

Hi there,

I’m having trouble understanding how to work with class variables across different files.

I have a parent class defined in file ‘game.rb’ which creates a variable ‘score’.
I have a sub class defined in file ‘TestGame.rb’ which requires the file ‘game.rb’
I have a file ‘start.rb’ that is creating an instance of sub class, and I need to access the variable ‘score’ from its parent class.

I feel like I’ve tried everything I can think of, and am coming up way short.

File ‘game.rb’ has the following code:

      class Game
        attr_accessor(:name, :score)

        def initialize(name)
          @name = name
          @score = nil
        end

        def win
          puts "You win!"
          score = 1
        end
      end

File ‘TestGame.rb’ has the following code:

    require_relative 'game'

    class TestGame < Game

      def initialize
      end

      def play()
        puts "This is my test game."
        win
     end
   end

File ‘start.rb’ has the following code:

    require_relative 'game'
    require_relative 'TestGame'

    TestGame.new.play
    TestGame.score

I’m able to get the files to load correctly and play the instance of my game, but once the game is over, I’m wanting to access the score, and that’s the piece that I can’t get to work.

What am I not understanding correctly or missing?

#2

I think in method win, you should make @score = 1 rather than writing score = 1.
Take a look:

        def win
          puts "You win!"
          @score = 1     # Modified line
        end
#3

I tried changing that to @score like you suggested, but I’m still getting a no method error, undefined method ‘score’ for TestGame:Class.

I’ve also created a getter method to try to access the variable, and it doesn’t appear to work either:

 def score
  @score
 end

I feel like I may be going about this the whole wrong way. Essentially, I’m trying to create a few subclasses of different mini games to play, have the user play a few of these games at random, and then sum up the total number of wins that a player gets. Is there a better way to accomplish this other than what I’m trying?

#4

You are trying to call an instance method on a class object.

Your code should be something like this:

game = TestGame.new
game.play
game.score
1 Like
#5

Thank you so much, that is what I didn’t understand correctly!