我在RubyMine中有这两个类:
book.rb
class Book
def initialize(name,author)
end
end
test.rb
require 'book'
class teste
harry_potter = Book.new("Harry Potter", "JK")
end
当我运行test.rb时,我收到此错误:
C:/Users/DESKTOP/RubymineProjects/learning/test.rb:3:in <class:Test>': uninitialized constant Test::Book (NameError)
from C:/Users/DESKTOP/RubymineProjects/learning/test.rb:1:in
'
来自-e:1:load'
from -e:1:in
'
答案 0 :(得分:17)
您收到错误是因为您的require 'book'
行需要其他地方的其他book.rb
,而且不会定义Book
类。
Ruby不会自动将当前目录包含在它将搜索require
的目录列表中,因此如果要在当前目录中需要文件,则应显式添加./
,即
require './book'
答案 1 :(得分:7)
您已经定义了初始化方法但忘记将值分配到实例变量中并且代码中的拼写错误触发了错误,将其修复为:
book.rb
class Book
def initialize(name,author)
@name = name
@author = author
end
end
test.rb
require './book'
class Test
harry_potter = Book.new("Harry Potter", "JK")
end
那么,您关注哪本书或资源?我认为你至少应该完成一本书,以获得关于Ruby和面向对象编程的正确知识。我会建议你和“红宝石之书”#39;开头。
答案 2 :(得分:0)
在Rails应用程序中,这个错误也可以通过重命名类而不重命名文件来匹配,这是我发现这个错误时的问题:
book.rb
class Book
def initialize(name, author)
end
end
book_test.rb
class BookTest
harry_potter = Book.new("Harry Potter", "JK")
end