Kask
Kask

Reputation: 63

How to run a method from another class in Ruby

Hi I try to make my first game in ruby :)

I have two files:

#"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

and second file

#"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()

The question is, how can I call class Game.name method from Start.play() class. The game goes deeper, and insted of 'exit(0)' it returns :symbol of another method from "Game" class that should work.

Upvotes: 0

Views: 1179

Answers (1)

Arie Xiao
Arie Xiao

Reputation: 14082

Make start readable for the Game class. DO NOT call exit(0) in your code unless it's really necessary. Instead, use some conditions to make sure the program runs to the end of script.

#"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

Use instance#method(...) to get a bounded method to that instance.

#"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()

Upvotes: 1

Related Questions