如何从另一个类中获取一个对象

时间:2019-08-15 10:51:14

标签: ruby

我有两节课。 Todo和TodoList。我从Todolist类中收到2条错误消息,我认为这是因为我尚未正确确定如何将对象从Todo传递到TodoList。如果是这种情况,我该怎么办?

我尝试设置变量并在Atom中运行测试以关闭要传递对象的位置(假设这就是我应该做的)。在简单地尝试按原样传递对象之后,我检查了命名结构是否正确。

这里是我现在拥有的代码:

class Todo

  def initialize(param)
    @param = param
  end

  def text
    return @param
  end
end

class TodoList

  def initialize
    @item_list = []
  end

  def add(item)
    @item = []
    @item << item
  end

  def print
    @item_list.each do |item|
      puts "* #{item}"
    end
  end
end

以下是错误消息:

 1) Q1. Todo list TodoList printing todos one todo prints a single todo with a bullet point
     Failure/Error: expect { todo_list.print }.to output("* get milk\n").to_stdout

       expected block to output "* get milk\n" to stdout, but output nothing
       Diff:
       @@ -1,2 +1 @@
       -* get milk

2) Q1. Todo list TodoList printing todos many todos prints the todos, separated by newlines
     Failure/Error: expect { todo_list.print }.to output(expected_output).to_stdout

       expected block to output "* get milk\n* get the paper\n* get orange juice\n" to stdout, but output nothing
       Diff:
       @@ -1,4 +1 @@
       -* get milk
       -* get the paper
       -* get orange juice

     # ./spec/question_1_spec.rb:63:in `block (5 levels) in <top (required)>'


以下是错误中提到的测试规范:

context "one todo" do
        it "prints a single todo with a bullet point" do
          todo_list.add(todo)

          expect { todo_list.print }.to output("* get milk\n").to_stdout
        end
      end

      context "many todos" do
        let(:todo_1) { Todo.new("get milk") }
        let(:todo_2) { Todo.new("get the paper") }
        let(:todo_3) { Todo.new("get orange juice") }
        let(:todo_list) { TodoList.new }

        let(:expected_output) { ["* get milk",
                                "* get the paper",
                                "* get orange juice"].join("\n") +
                               "\n" }

        it "prints the todos, separated by newlines" do
          todo_list.add(todo_1)
          todo_list.add(todo_2)
          todo_list.add(todo_3)

          expect { todo_list.print }.to output(expected_output).to_stdout
        end

所以我应该得到两件事作为输出:

包含一项的列表:

  • 喝牛奶

以及包含3个项目的列表:

  • 喝牛奶
  • 获取论文
  • 拿橙汁

但实际上我什么也没得到。

如何将一个对象从一个类传递到另一个类(假设这是问题所在),并且如果不是问题,那是什么?

谢谢

1 个答案:

答案 0 :(得分:1)

add方法不正确。在initialize方法中,将@item_list设置为一个空数组。但是,您没有在add方法中向该变量添加数据,而是在@item_list方法中使用了print变量。因此,在add方法中,您需要使用@item_list变量而不是@item变量。

class TodoList
  ..
  def add(item)
    @item_list << item
  end
  ..
end
相关问题