假设我有三个类,每个类都在自己的文件中定义。例如ClassA.rb 中的 ClassA 等...
class ClassA
def initialize
end
def printClassA
puts "This is class A"
end
end
class ClassB
def initialize
end
def printClassB
puts "This is class B"
end
end
class ClassC
def initialize
end
def bothClasses
a = ClassA.new
b = ClassB.new
a.printClassA
b.printClassB
end
end
如您所见,ClassC 需要其他两个类才能正常运行。我假设,需要有一种方法来导入/包含/加载 ClassC 中的其他两个类。
我是 Ruby 的新手,我已经尝试了 load/include/require 的每一种排列,但我不知道如何让它运行。
我通常只得到:
classc.rb:2:in `<class:ClassC>': uninitialized constant ClassC::ClassA (NameError)
from classc.rb:1:in `<main>'
或者我的 import/include/require 语句的语法错误。
使用 Windows 7、Ruby 1.9.2、RadRails,所有文件都在同一个项目和源文件夹中。
如果这个问题与此处的其他一些问题相似,我很抱歉,但解决“未初始化常量”的大部分答案是“只需要文件”。我试过了,但没有用。
最佳答案
我认为您的问题是 $:
,控制 require
查找文件的位置的变量,在 Ruby 1.9.2 和更高版本中不再包含当前目录(出于安全原因)。要告诉 Ruby 在哪里寻找文件,您需要执行以下操作之一:
require_relative 'ClassA' # which looks in the same directory as the file where the method is called
# or #
require './ClassA' # which looks in the current working directory
关于ruby - 无法在 Ruby : uninitialized constant (NameError) 中将一个类包含到另一个类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4910851/