Ruby:在类之间使用变量

标签 ruby

我正在制作一个基于文本的简短游戏,作为基于我目前所学 Ruby 的额外学分练习,但我无法让类在彼此之间读写变量。我已经广泛阅读并搜索了有关如何执行此操作的说明,但我运气不佳。我试过使用 @ 实例变量和 attr_accessible 但我无法弄明白。到目前为止,这是我的代码:

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

我想让不同的 Room 类更改 @room_count 变量,以便 Game 类知道下一个去哪个房间。我也试图在不实现类继承的情况下做到这一点。谢谢!

最佳答案

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

关于Ruby:在类之间使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12573843/

相关文章:

ruby - 在 Ruby 脚本中执行 shell 脚本命令

ruby-on-rails - database.yml 的 Ruby 和 Rails yaml 解析器错误

ruby-on-rails - 如何通过 RVM 安装 Rails 4(最终版)和最新版本的 Ruby?

ruby-on-rails - 数据库文件在哪里? rails

ruby - 在 ruby​​ 中,你将相关符号(如 java 中的枚举)放在哪里?

具有多个指向相同值的键的 Ruby 哈希

Ruby 电子邮件编码和引用打印内容

ruby - 为什么乘法在 Ruby 中并不总是可交换的?

ruby - 使用yield 改变函数内部的参数

ruby - 遍历实例变量,如何更改它们?