如何从另一个类在Ruby中运行的方法
问题描述:
您好我尽量让我的第一场比赛在红宝石:)如何从另一个类在Ruby中运行的方法
我有两个文件:
#"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)'它返回:应该工作的“游戏”类的另一种方法的符号。
答
制作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()
在Start类中初始化方法,@game是Game类的实例,但是问题是:name是什么? –
:name是指游戏规则中名为“name”的方法,或者它应该指向。我很在这。 – Kask