Friso1990 Friso1990 - 6 months ago 14
Ruby Question

How do I import ruby classes into the main file?

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

Answer

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.