How do I import ruby classes into the main file?
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.
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.