Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Uninitialized Constant NameError for Class Name

Tags:

ruby

I want to inherit a sub-class from a parent-class.

Here is my code. 3 classes are created in 3 separate files.

class Transportation
#codes
end

class Plane < Transportation
#codes
end

class Boat < Transportation
#codes
end

And when I was running this code, I got the error for Boat, but no issue for Plane when I only have Plane created:

uninitialized constant Transportation (NameError)

Can anyone help me with this issue?

Thanks

like image 338
Victor Xiong Avatar asked May 13 '13 02:05

Victor Xiong


1 Answers

There is no reason for this code to fail, unless the definition of Transportation is in another file.

If that is the case, and these are in different files, don't forget to require the file with the Transportation class before the other file with the usage in it.

As you mentioned, there are three different files.

You can create a file that has the required libraries. Perhaps it is in your bin/transport_simulator.rb file.

require 'transportation'
require 'boat'
require 'plane'

Now they will be required in the proper order, and the files with the classes that subclass Transportation will know about that class.

like image 121
vgoff Avatar answered Nov 16 '22 11:11

vgoff