Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I import ruby classes into the main file?

Tags:

ruby

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
like image 242
Friso Avatar asked May 31 '16 02:05

Friso


People also ask

How do you insert a class in Ruby?

To put a class in a separate file, just define the class as usual and then in the file where you wish to use the class, simply put require 'name_of_file_with_class' at the top. For instance, if I defined class Foo in foo. rb , in bar.

How do I import a module into Ruby?

include is the most used and the simplest way of importing module code. When calling it in a class definition, Ruby will insert the module into the ancestors chain of the class, just after its superclass.


1 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.

like image 102
13aal Avatar answered Sep 18 '22 19:09

13aal