Syl Syl - 3 months ago 5x
Ruby Question

Calling another ruby file that is not a gem

I want to create a static ruby class with a library of function. I am on Vista with ruby 1.9.2

My class is this one :

class TestClass

def say_hello
puts "say hello"

in a TestClass.rb file (I assume I am correct as all ruby tutorials on classes are a complete mess putting everything in a single magic something (file?) as if IRB was the begining and the end of all thing).

My ruby
(yes I come from Java) or program entry or wathever it is called in ruby is :

require 'TestClass.rb'

puts "start"

But it fails with :

C:\ruby_path_with_all_my_classes>ruby classuser.rb
<internal:lib/rubygems/custom_require>:29:in `require': no such file to load --
TestClass.rb (LoadError)
from <internal:lib/rubygems/custom_require>:29:in `require'
from classuser.rb:1:in `<main>'

How does it work? Is it possible to call other files in Ruby or are you trapped in only one file containing all your classes?


In 99% of all cases when a computer tells you that it couldn't find a thing, it is because the thing isn't there. So, the first thing you need to check is whether there actually is a file named TestClass.rb somewhere on your filesystem.

In 99% of the rest of the cases, the computer is looking in the wrong place. (Well, actually, the computer is usually looking in the right place, but the thing it is looking for is in the wrong place). require loads a file from the $LOAD_PATH, so you have to make sure that the directory that the file TestClass.rb is in actually is on the $LOAD_PATH.

Alternatively, if you do not want to require a file from the $LOAD_PATH but rather relative to the position of the file that is doing the requireing, then you need to use require_relative.

Note, however, that your code won't work anyway, since say_hello is in instance method of instances of the TestClass class, but you are calling it on the main object, which is an instance of Object, not TestClass.

Note also that standard naming conventions of Ruby files are snake_case, in particular, the snake_case version of the primary class/module of the file. So, in your case, the file should be named test_class.rb. Also, require and require_relative figure out the correct file extension for themselves, so you should leave off the .rb. And thirdly, standard Ruby coding style is two spaces for indentation, not four.

None of these will lead to your code not working, of course, since it is purely stylistic, but it may lead to people being unwilling to answer your questions, since it shows that you don't respect their community enough to learn even the most basic rules.