我想制作一个小型且简单的待办事项清单程序。我已经为此空白了两个小时。这是仪器:
> # Write a program that keeps a list of todos. It should:
> # * Have two classes:
> # * `Todo`
> # * Has two methods:
> # * `initialize`: Creates a new todo object. Takes a string as a
> # parameter and stores it on the todo object.
>
> # * `text`: Takes no parameters. Returns the string that was
> # stored when the todo object was created.
>
>
> # * `TodoList`
> # * Has three methods:
> # * `initialize`: Creates a new todo list object. Takes no parameters.
>
> # * `add`: Takes a todo object as a parameter. Stores it on the
> # todo list object.
>
> # * `print`: Takes no parameters. Creates a string of all the
> # stored todos, one per line. Each line should start with a
> # `* `. `puts`es the string.
>
> # * e.g.
> # ```
> # * get milk
> # * get the papers
> # ```
这是我尝试的程序代码:
class Todo
def initialize(todo)
@todo = todo
end
def text
@todo
end
end
class TodoList
def initialize
@todo_list = []
end
def add(todo)
@todo_list << Todo.new(todo)
end
def print
@todo_list.each do |x|
puts "* #{x}"
end
end
end
我知道我在这里遗漏了一些东西,但是我似乎看不到什么。.当我测试它时,我通过了除2之外的所有测试,两个失败的测试都涉及TodoList类中描述的打印方法
答案 0 :(得分:2)
对您正在发生的事情有所了解。
class Todo
def initialize(todo)
@todo = todo # This sets your instance variable @todo to whatever you passing, you will probably want to add a check to make sure you only accept strings
end
def text
@todo # The text method is returning whatever the @todo variable is, in this case since you are passing a string, it is returning a string
end
end
class TodoList
def initialize
@todo_list = [] # When you are initializing your TodoList you are creating an array called @todo_list
end
def add(todo)
@todo_list << Todo.new(todo) # When you call this method you are adding a new instance of your Todo class
end
def print
# Here you are iterating through your array @todo_list, which we established earlier is an array of your Todo Class variables
@todo_list.each do |x| # Pro tip, try to stay away from using names like 'x' or 'y' use more descriptive names
# Your 'x' variable here is one of your Todo classes instances
puts "* #{x.text}" # As defined in your Todo class, you will need to call the text method to retrieve the text you stored in your class
end
end
end
list = TodoList.new # Here we create a new instance of your TodoList class
list.add('Buy Pizza') # Here we can add items onto your todo list
list.add('Buy Pie')
list.add('Buy Potato')
list.print # This is how you will print all the items you added to your TodoList
这将返回
* Buy Pizza
* Buy Pie
* Buy Potato