File importing tip

In ruby, you can import a file into your class, by putting:

require "name_of_the_file_without_the_extension"

at the top of your class definition file. This allows you to import another class file into this class file, so you can access the methods in the other class. Pretty cool.

BUT, it can only import ruby files. Do NOT try to require other file types, because, in the background, ruby expects the file name to end with .rb. If it is a different kind of file, ruby will try to import a file with the file’s filename, but with the .rb extension. So, if you have a file named:

phone_numbers.txt

And you add this to a ruby class file:

require “phone_numbers”

ruby is going to throw an error when you try to use that class file. It’ll look something like:

/ridiculously/long/path…/custom_require.rb:36:in `require’: cannot load such file — words

If you need to use a different kind of file, pass its file name into initialize.

def initialize(filename)
   @filename = filename
end

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Skip to content