2014-03-13 36 views
0

您好我儘量讓我的第一場比賽在紅寶石:)如何從另一個類在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)'它返回:應該工作的「遊戲」類的另一種方法的符號。

+0

在Start類中初始化方法,@game是Game類的實例,但是問題是:name是什麼? –

+0

:name是指遊戲規則中名爲「name」的方法,或者它應該指向。我很在這。 – Kask

回答

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() 
相關問題