17

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>'
ggorlen
  • 44,755
  • 7
  • 76
  • 106
TheKilz
  • 321
  • 1
  • 3
  • 10

3 Answers3

29

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'
smathy
  • 26,283
  • 5
  • 48
  • 68
  • 3
    You should also [accept my answer](http://stackoverflow.com/help/accepted-answer) if it's the best one and helped you fix your problem. See [What should I do when someone answers my question?](http://stackoverflow.com/help/someone-answers) for full details on all this stuff. – smathy Mar 18 '15 at 22:42
10

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:

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

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.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Sharvy Ahmed
  • 7,247
  • 1
  • 33
  • 46
7

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
JP.
  • 257
  • 1
  • 3
  • 8