I'm trying to learn how to program with Ruby and I want to create separate files for separate classes, but when I do I get the following message:

NameError: uninitialized constant Book
const_missing at org/jruby/RubyModule.java:2677

(root) at /Users/Friso/Documents/Projects/RubyApplication1/lib/main.rb:1

However, it works if I put the class directly into the main file. How can I solve this?

Main code:

book1 = Book.new("1234", "Hello", "Ruby") book2 = Book.new("4321", "World", "Rails") book1.to_string book2.to_string 

Class code:

class Book def initialize(isbn,title,author) @book_isbn=isbn @book_title=title @book_author=author end def to_string puts "Title: #@book_title" puts "Author: #@book_author" puts "ISBN: #@book_isbn" end end 
1

2 Answers

In order to include classes, modules, etc into other files you have to use require_relative or require (require_relative is more Rubyish.) For example this module:

module Format def green(input) puts"\e[32m#{input}[0m\e" end end 

Now I have this file:

require_relative "format" #<= require the file include Format #<= include the module def example green("this will be green") #<= call the formatting end 

The same concept goes for classes:

class Example attr_accessor :input def initialize(input) @input = input end def prompt print "#{@input}: " gets.chomp end end example = Example.new(ARGV[0]) 

And now I have the main file:

require_relative "class_example" example.prompt 

In order to call any class, or module from another file, you have to require it.

I hope this helps, and answers your question.

You need to instruct the Ruby runtime to load the file that contains your Book class. You can do this with require or require_relative.

The latter is better in this case, because it loads the file relative to the directory in which the file containing the require is specified. Since that's probably the same directory, you can just require_relative the file name, without the .rb extension by convention.

You can google 'require vs require_relative ruby' to find out more about the differences.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy