运行 2 个方法具有已定义的实例变量,但仍会产生未定义的局部变量

running 2 methods with defined instance variables but still coming up with undefined local variable

我是初学者,我尝试浏览所有在线资源。即使我添加了“@”符号,以便 'title' 和 'author' 变量应用第二种方法(描述),我也不知道我做错了什么。不知道为什么运行 此代码出现 NameError - 未定义的局部变量或方法“标题”#。有任何想法吗?谢谢

class Book
  def set_title_and_author(title,author)
    @title = title  
    @author = author
  end  

  def description
    puts "#{title} was written by #{author}" 
  end
end

这里有一些规格:

describe "Book" do
  describe "description" do
    it "should return title and author in description" do
      book = Book.new
      book.set_title_and_author("Ender's Game","Orson Scott Card")
      expect( book.description ).to eq("Ender's Game was written by Orson Scott Card")
    end
  end
end

设置和获取实例变量时需要使用@:

class Book
  def set_title_and_author(title, author)
    @title = title  
    @author = author
  end  

  def description
    puts "#{@title} was written by #{@author}" 
  end
end