24

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

4
  • What's the code that is causing the error?
    – thank_you
    Commented May 13, 2013 at 2:05
  • show your code if possible
    – sunny1304
    Commented May 13, 2013 at 2:09
  • I've tried to create a really simple class, and the same error, so it's nothing to do with the code. thanks Commented May 14, 2013 at 23:34
  • Still show your code. You won't know what you aren't seeing, as you are asking for help, but we might be able to spot it immediately. (Such as identifying that you have separate files, though you did not directly indicate this.)
    – vgoff
    Commented May 14, 2013 at 23:38

1 Answer 1

38

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.

6
  • yea, u r right, the codes work after I required the Transportation, but do u know why I don't need to do this when I only have Plane created and inherit from Transportation? Thank you. Commented May 14, 2013 at 23:35
  • Are Transportation and Plane in the same file?
    – vgoff
    Commented May 14, 2013 at 23:36
  • 2
    Well, this would be a good argument for showing that in the problem description. :) In each file, you can require the Transportation, you will have to otherwise guarantee the load/require order of these files. I will update my answer.
    – vgoff
    Commented May 15, 2013 at 0:27
  • 2
    @LingchenXiong if this answered the question, you should mark it as the accepted answer. :)
    – theIV
    Commented May 15, 2013 at 0:33
  • It's my first day writing Ruby today, and I came across the same error. My problem was that my class file was in lower case, where Ruby expects it to start with upper case.
    – shaunlim
    Commented Jul 29, 2014 at 21:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.