Uninitialized constant error in Ruby class

TheKilz picture TheKilz · Mar 18, 2015 · Viewed 53.7k times · Source

I have these two classes in 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

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 `<top (required)>'
from -e:1:in `load'
from -e:1:in `<main>'

Answer

smathy picture smathy · Mar 18, 2015

You're getting the error because your require 'book' line is requiring some other book.rb from somewhere else, which doesn't define a Book class.

Ruby does not automatically include the current directory in the list of directories it will search for a require so you should explicitly prepend a ./ if you want to require a file in the current directory, ie.

require './book'