ruby-on-railsrubyruby-on-rails-3rubyminerubymine-7

Uninitialized constant error in Ruby class


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>'

Solution

  • 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:

    book.rb

    class Book
      def initialize(name, author)
      end
    end
    

    book_test.rb

    class BookTest
      harry_potter = Book.new("Harry Potter", "JK")
    end