使用io控制台访问Ruby类方法

时间:2014-06-15 21:41:15

标签: ruby class io

我在Ruby中创建一个简单的任务管理器,并且无法在我创建的对象上运行类方法。这是我的后端代码:

class TM::Project
  attr_accessor :name, :pid, :tasks
  @@projects = []

  def initialize(name=nil)
    @name = name
    @pid = @@projects.size
    @tasks = []
    @@projects << self
  end

  def add_task(priority, description)
    task = TM::Task.new(priority, description)
    @tasks << task
  end
end

class TM::Task
  attr_accessor :tid, :description, :priority, :status, :creation_date
  @@tasks = []

  def initialize(priority, description)
    @description = description
    @priority = priority
    @tid = @@tasks.size
    @@tasks << self
    @status = "incomplete"
    @creation_date = Time.now
  end
end

以下是控制台的代码:

require_relative 'lib/task-manager.rb'

class Task_io
  @@io_projects = []

  def start
    puts "Welcome to Task Manager.  How may we assist you?\n\n"

    puts "Available Commands: \n"
    puts "  create NAME - Create a new project with name=NAME"
    puts "  add PID PRIORITY DESC - Add a new task to project with id=PID"

    puts 'Enter request>'
    req = gets.chomp
    input = req.split

    if input[0] == 'create'
        proj = TM::Project.new(input[1])
        puts "#{proj.name} was created with ID=#{proj.pid}"
        @@io_projects << proj
        self.start
    elsif input[0] == 'add'
        i = 0
        proj_id = input[1].to_i
        @@io_projects[proj_id].add_task(input[2], input[3].to_s)
        puts "#{input[3].to_s} was assigned TID #{@@tasks[i + 1]}"
        i += 1
        self.start
    else
      puts "Invalid request, please try again"
      self.start
    end
  end
end

我能够创建项目,但是当我尝试向项目添加任务时,我收到以下错误:

undefined method `add_task' for nil:NilClass

我是否错误地访问了该对象?

0 个答案:

没有答案