Uninitialized constant error in Ruby class
Asked Answered
R

4

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>'
Rainmaker answered 18/3, 2015 at 21:27 Comment(0)
C
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
Cloudy answered 15/3, 2018 at 21:19 Comment(0)
P
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'
Psalterium answered 18/3, 2015 at 21:51 Comment(1)
You should also accept my answer if it's the best one and helped you fix your problem. See What should I do when someone answers my question? for full details on all this stuff.Psalterium
M
9

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.

Maturate answered 18/3, 2015 at 21:31 Comment(0)
C
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
Cloudy answered 15/3, 2018 at 21:19 Comment(0)
G
0

Another rookie mistake (which I made) is to define a class inside a module but forgetting to put it inside a folder:

# This file should go inside a folder called `SomeModule` and it should be named `some_class.rb`
module SomeModule
  class SomeClass
    # ...
  end
end

I know it's not your case because of the class definition but I wanted to share it anyway.

Gignac answered 23/1 at 11:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.