首页 > 解决方案 > Ruby - 使用类和方法的简单 ToDo 列表程序遇到问题

问题描述

我想做一个小而简单的待办事项列表程序。我已经空白了几个小时了。以下是说明:

> # 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 类中描述的打印方法。

标签: ruby

解决方案


对您正在发生的事情有点失望。

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

推荐阅读