Ruby: Using variables between classes

◇◆丶佛笑我妖孽 提交于 2021-01-29 04:08:50

问题


I am making a short, text-based game as an extra credit exercise based on the Ruby I have learned so far and I'm having trouble getting classes to read and write variables between each other. I have read extensively and searched for clarification on how to do this but I haven't had much luck. I have tried using @ instance variables and attr_accessible but I can't figure it out. Here is my code so far:

class Game
  attr_accessor :room_count

  def initialize
    @room_count = 0
  end

  def play
    while true
      puts "\n--------------------------------------------------"

      if @room_count == 0
        go_to = Entrance.new()
        go_to.start
      elsif @room_count == 1
        go_to = FirstRoom.new()
        go_to.start
      elsif @room_count == 2
        go_to = SecondRoom.new()
        go_to.start
      elsif @room_count == 3
        go_to = ThirdRoom.new()
        go_to.start
      end
    end
  end

end

class Entrance

  def start
    puts "You are at the entrance."
    @room_count += 1
  end

end

class FirstRoom

  def start
    puts "You are at the first room."
    @room_count += 1
  end

end

class SecondRoom

  def start
    puts "You are at the second room."
    @room_count += 1
  end

end

class ThirdRoom

  def start
    puts "You are at the third room. You have reached the end of the game."
    Process.exit()
  end

end

game = Game.new()
game.play

I want to have the different Room classes change the @room_count variable so that Game class knows which room to go to next. I am also trying to do this without implementing class inheritance. Thanks!


回答1:


class Room
  def initialize(game)
    @game = game
    @game.room_count += 1
  end

  def close
    @game.room_count -= 1
  end
end

class Game
  attr_accessor :room_count

  def initialize
    @room_count = 0
  end

  def new_room
    Room.new self
  end
end

game = Game.new
game.room_count # => 0
room = game.new_room
game.room_count # => 1
room.close
game.room_count # => 0


来源:https://stackoverflow.com/questions/12573843/ruby-using-variables-between-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!