无法在Ruby中将一个类包含在另一个类中:未初始化的常量(NameError)

我有三个类,每个定义在自己的文件中.例如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,所有文件都在同一个项目和源文件夹中.

如果这个问题类似于这里的其他一些问题,我很抱歉,但解决“未初始化常数”的大多数答案是“只需要文件”.我已经尝试了,它不工作.

解决方法

我认为你的问题是$:,控制where需要查找文件的变量,不再包含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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...