如何从Ruby中的另一个类运行方法

时间:2014-03-13 06:11:35

标签: ruby class methods

您好我尝试用红宝石制作我的第一个游戏:)

我有两个文件:

#"game.rb" with code:
class Game
  attr_accessor :imie, :klasa, :honor
  def initialize(start_scena)
    @start = start_scena
  end

  def name()
    puts "Some text"
    exit(0)
  end
end

和第二个文件

#"game_engine.rb"
require_relative 'game.rb'

class Start
  def initialize
    @game = Game.new(:name)
  end

  def play()
    next_scena = @start

    while true
      puts "\n---------"
      scena = method(next_scena)
      next_scena = scena.call()
    end
  end
end

go = Start.new()
go.play()

问题是,如何从Start.play()类调用类Game.name方法。游戏更深入,并且出现了退出(0)'它返回:来自" Game"的另一种方法的符号应该工作的班级。

1 个答案:

答案 0 :(得分:1)

使start类的Game可读。除非确实有必要,否则请勿在代码中致电exit(0)。相反,使用一些条件来确保程序运行到脚本结束。

#"game.rb" with code:
class Game
  attr_accessor :imie, :klasa, :honor
  attr_reader :start
  def initialize(start_scena)
    @start = start_scena
  end

  def name()
    puts "Some text"
    :round2
  end

  def round2
    puts "round2"
    nil
  end
end

使用instance#method(...)为该实例获取有界方法。

#"game_engine.rb"
require_relative 'game.rb'

class Start
  def initialize
    @game = Game.new(:name)
  end

  def play()
    next_scene = @game.start

    while next_scene
      puts "\n---------"
      scene = @game.method(next_scene)
      next_scene = scene.call()
    end
  end
end

go = Start.new()
go.play()