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"
end
end
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 main() (yes I come from Java) or program entry or wathever it is called in ruby is :
require 'TestClass.rb'
puts "start"
say_hello
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.rbsomewhere 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).
requireloads a file from the$LOAD_PATH, so you have to make sure that the directory that the fileTestClass.rbis in actually is on the$LOAD_PATH.Alternatively, if you do not want to
requirea file from the$LOAD_PATHbut rather relative to the position of the file that is doing therequireing, then you need to userequire_relative.Note, however, that your code won’t work anyway, since
say_hellois in instance method of instances of theTestClassclass, but you are calling it on themainobject, which is an instance ofObject, notTestClass.Note also that standard naming conventions of Ruby files are
snake_case, in particular, thesnake_caseversion of the primary class/module of the file. So, in your case, the file should be namedtest_class.rb. Also,requireandrequire_relativefigure 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.