没有方法错误,从不同的类调用方法,传递参数

时间:2013-12-24 02:29:09

标签: ruby

有人可以帮一个新手吗?我收到了错误;

: undefined method `computer_name' for nil:NilClass (NoMethodError)

我想在ruby中用.method_name调用方法?
是因为我的初始化方法不正确吗?没有正确传递参数?

load 'admin_logic.rb'
load 'computer_logic.rb'
load 'user_logic.rb'

class TicTacToe
  def initialize(admin_object, computer_object, user_object)
    admin_object = Admin.new
    computer_object = ComputerLogic.new
    user_object = UserLogic.new
    @new_game = TicTacToe.new(admin_object, computer_object, user_object)
  end
end

puts "Hello, I\'m " + @new_game.computer_name + ", let\'s play Tic Tac Toe!  What is your name?"

puts "Great " + @new_game.user_name + ", you\'ll be " + @new_game.user_sign + ".  Please choose where you want to go."

puts 'The game board is the following, please remember!'
puts ' a1 | a2 | a3'
puts " --- --- ---"
puts ' b1 | b2 | b3'
puts " --- --- ---"
puts ' c1 | c2 | c3'

@new_game.user_sign
@new_game.computer_sign
@new_game.game_board
@new_game.winning_propositions

while @new_game .computer_win != true do
  @new_game.user_turn
  @new_game.draw_game_outcome
  @new_game.player_first_turn_check?
  @new_game.draw_game_outcome
end

我打电话给我的班级 - ADMIN.RB

class Admin
  def computer_name
    @computer_name = "Watson"
  end
end

2 个答案:

答案 0 :(得分:2)

您目前正在设置班级的@new_game INSIDE 。您正试图在课程中使用 OUTSIDE 。变量范围不允许您这样做。

您想要做的是以下内容。

class TicTacToe
  def initialize(admin_object, computer_object, user_object)
    admin_object = Admin.new
    computer_object = ComputerLogic.new
    user_object = UserLogic.new
  end
end

@new_game = TicTacToe.new(admin_object, computer_object, user_object)

这将创建一个TicTacToe类的实例,然后您可以使用已定义的方法。

答案 1 :(得分:0)

这不是对象的工作方式。你的初始化程序正在调用它自己开始。

这可能是一个更好的起点,但请花点时间做一些关于OOP的基本阅读:

class Admin
  def name
    "Watson"
  end
  alias_method :to_s, :name
end

class TicTacToe
  attr_reader :admin_object, :computer_object, :user_object

  def initialize
    @admin_object = Admin.new
    @computer_object = ComputerLogic.new
    @user_object = UserLogic.new
  end
end

@new_game = TicTacToe.new

查看一些教程,例如。 https://www.ruby-lang.org/en/documentation/quickstart/2/