类名称的 Ruby 未初始化常量名称错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16513969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:56:34  来源:igfitidea点击:

Ruby Uninitialized Constant NameError for Class Name

ruby

提问by Victor Xiong

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

我想从父类继承子类。

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

这是我的代码。在 3 个单独的文件中创建了 3 个类。

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

谢谢

回答by vgoff

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

这段代码没有理由失败,除非 的定义Transportation在另一个文件中。

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

如果是这种情况,并且这些文件位于不同的文件中,请不要忘记Transportation在包含用法的其他文件之前require 带有类的文件。

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.rbfile.

您可以创建一个包含所需库的文件。也许它在您的bin/transport_simulator.rb文件中。

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.

现在,它们将以正确的顺序被需要,并且带有子类 Transportation 的类的文件将了解该类。