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)
4
  • What's the code that is causing the error? Commented May 13, 2013 at 2:05
  • show your code if possible 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.) 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.

Sign up to request clarification or add additional context in comments.

6 Comments

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.
Are Transportation and Plane in the same file?
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.
@LingchenXiong if this answered the question, you should mark it as the accepted answer. :)
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.