Ruby 类中的未初始化常量错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29133040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uninitialized constant error in Ruby class
提问by TheKilz
I have these two Classes in RubyMine:
我在 RubyMine 中有这两个类:
book.rb
书.rb
class Book
def initialize(name,author)
end
end
test.rb
测试文件
require 'book'
class teste
harry_potter = Book.new("Harry Potter", "JK")
end
When I run test.rb, I get this error:
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'
from -e:1:in load'
from -e:1:in'
当我运行 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' from -e:1:in load'
from -e:1:in'
采纳答案by Sharvy Ahmed
You have defined the initialize method but forgot to assign the values into instance variables and a typo in your code triggered the error, fixed it as:
您已经定义了 initialize 方法,但忘记将值分配给实例变量,并且代码中的错字触发了错误,将其修复为:
book.rb
书.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
So, which book or resource are you following? I think you should at least complete a book to get proper knowledge of Ruby and Object Oriented Programming. I would suggest you 'The Book of Ruby' to start with.
那么,您在关注哪本书或资源?我认为你至少应该完成一本书来获得 Ruby 和面向对象编程的正确知识。我建议你从“The Book of Ruby”开始。
回答by smathy
You're getting the error because your require 'book'line is requiring some other book.rbfrom somewhere else, which doesn't define a Bookclass.
您收到错误是因为您的require 'book'线路需要book.rb来自其他地方的其他线路,而该线路并未定义Book类。
Ruby does not automatically include the current directory in the list of directories it will search for a requireso you should explicitly prepend a ./if you want to require a file in the current directory, ie.
Ruby 不会自动将当前目录包含在它将搜索的目录列表中,require因此./如果您想在当前目录中需要一个文件,您应该明确地预先添加 a ,即。
require './book'
回答by JP.
In a Rails app this error can also be caused by renaming the class without renaming the file to match, which was my issue when I found this error:
在 Rails 应用程序中,这个错误也可能是由于重命名类而不重命名文件来匹配,这是我发现这个错误时的问题:
book.rb
书.rb
class Book
def initialize(name, author)
end
end
book_test.rb
book_test.rb
class BookTest
harry_potter = Book.new("Harry Potter", "JK")
end

