所以,这是我的问题。当我在程序运行器的开头创建一个新的List类时,它应该创建一个新的数组(all_tasks
)。每次添加新任务时,都应该将任务推送到数组。然后,当我显示数组时,它应列出每个任务。
问题在于我使用write_to_file
方法。我收到错误Undefined local variable or method 'all_tasks'
。我做了另一个方法案例,我可以看看数组,看起来新任务没有被推入数组。然而,当我使用show_tasks
方法时,它能够列出数组中的所有内容。
如果有人不能只是抓住我的解决方案而且还要详细说明,我会很感激。我还是Ruby的初学者。
作为旁注,show_tasks
方法还会列出数组中的每个项目两次,一次使用puts
,然后再次使用 ## Classes ##
#List Class - Used for anything involving the list
class List
attr_accessor :all_tasks
def initialize
@all_tasks = Array.new
end
def add(task)
all_tasks << task
end
def show_tasks
all_tasks.each do |x|
puts "- #{x}"
end
end
end
#Task Class - Used for anything involving Tasks
class Task
attr_reader :description
alias to_s description
def initialize(description)
@description = description
end
end
## Modules ##
module Promptable
def prompt(message = "What would you like to do?", symbol = ">: ")
print "#{message}\n"
print symbol
gets.chomp
end
def show_menu
menu
end
end
module Menu
def menu
puts "\nHere's a list of options that you can choose from: \n
'add' - Add a task to the list \n
'write' - Write the list to a file \n
'show' - Shows current tasks in list \n
'q' - Quits from current session \n
\n Please Select an option"
end
end
#Methods - various methods
def desc_to_s
description
end
def write_to_file(filename)
if all_tasks == nil
puts "Error - Array is nil"
else
IO.write(filename, @all_tasks.map(&:desc_to_s).join("\n"))
end
end
#Program Runner
if __FILE__ == $PROGRAM_NAME
include Menu
include Promptable
my_list = List.new
puts "\nWelcome to do ToDoLoo! Create your ToDo List \n"
until ['q'].include?(user_input = prompt(show_menu).downcase)
case user_input
# Developer only controls
when 'devshowtask'
my_list.each do |x|
puts "#{x}"
end
when 'add'
my_list.add(Task.new(prompt("What task would you like to create?")))
when 'show'
puts "Here's a current list of all your tasks:\n"
puts my_list.show_tasks
prompt("Press enter to continue")
when 'menu'
prompt(show_menu)
when 'write'
write_to_file(prompt("What would you like to name the file"))
else puts "\nThat is not a valid command"
end
end
end
。
{{1}}
答案 0 :(得分:1)
write_to_file
是模块菜单的一种方法,但是菜单不是在列表中混合,它不了解all_tasks
。另外,这一行
if all_tasks == nil
Ruby中的就像
一样if all_tasks.nil?
或
unless all_tasks
答案 1 :(得分:0)
attr_accessor
只生成两个方法,一个getter和一个setter。执行all_tasks << task
时,将调用getter,并返回@all_tasks的当前值,即匿名数组。然后将task
添加到该数组中。 (该数组是从add
隐式返回的,但我认为这无济于事。)请注意,@ all_tasks未被修改。
你可以这样做:
all_tasks = all_tasks << task
答案 2 :(得分:0)
感谢@dax,问题是调用了write_to_file
方法而没有调用数组来调用它。
而不是write_to_file
案件中的'write'
,而不应该是my_list.write_to_file