我正在使自己成为Ruby中的任务列表并且收到此错误
You have created a new list
todo.rb:13:in `<class:List>': undefined method `add' for #<List:0xea5520> (NoMethodError)
from todo.rb:9:in `<main>'
运行我的代码
class Task
attr_accessor :description
def initialize(description)
@description = description
end
end
class List
def initialize(all_tasks)
@all_tasks = []
attr_accessor :all_tasks
end
def add(task)
all_tasks << task
end
if __FILE__ == $0
my_list = List.new
puts 'You have created a new list'
add(Task.new('Make tutorial video'))
puts 'Added sample task to Todo List'
end
end
我根据人们的建议改变了它,但我现在得到了这个
todo.rb:10:in `initialize': wrong number of arguments (0 for 1) (ArgumentError)
from todo.rb:19:in `new'
from todo.rb:19:in `<class:List>'
from todo.rb:9:in `<main>'
我正在通过一个论证,不是吗?
答案 0 :(得分:0)
尝试没有“my_list”的对象,就像这样
add(Task.new('Make tutorial video'))
答案 1 :(得分:0)
我想你想要那样做
def add(task)
all_tasks << task
end
答案 2 :(得分:0)
我在irb上尝试过以下操作,但它确实有用。
class Task
attr_accessor :description
def initialize(description)
@description = description
end
end
class List
attr_accessor :all_tasks
def initialize(all_tasks)
@all_tasks = []
end
def add(task)
all_tasks << task
end
my_list = List.new([1,2])
puts 'You have created a new list'
my_list.add(Task.new('Make tutorial video'))
puts 'Added sample task to Todo List'
end