Victor Xiong
Victor Xiong

Reputation: 325

Ruby Uninitialized Constant NameError for Class Name

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

Upvotes: 24

Views: 64077

Answers (1)

vgoff
vgoff

Reputation: 11313

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.

Upvotes: 38

Related Questions