我使用的是Ruby 2.0,我有两个文件:hello.rb
& assets/display.rb
。
hello.rb的:
class Hello
def self.run_it(name)
ui = Display.new(name)
ui.say_hi
end
end
require_relative "assets/display"
Hello.run_it("Someone")
资产/ display.rb :
class Hello::Display
def initialize(name = "World")
@name = name
end
def say_hi
puts "Hello #{@name}"
end
end
如果在hello.rb中我在require_relative "assets/display"
(第1行)之前移动class Hello
,ruby hello.rb
会输出uninitialized constant
错误。这是为什么?在需要外部文件时,最佳做法是什么?require_relative
这个简短示例中的require
正确方法(vs require "./some_file"
和{{1}})是什么?
答案 0 :(得分:3)
标准做法是将所有或大部分require语句放在文件的顶部。应该设计文件,以便尽可能减少对其他文件的依赖。
您遇到的问题是您已将文件display.rb
设计为依赖于班级Hello
。
当你这样说时:
class Hello::Display
end
与以下内容相同:
class Hello
class Display
end
end
但不同之处在于,在第一种情况下需要先定义Hello
,然后才能说出Hello::Display
。由于当您将require放在文件顶部时未定义Hello
,您将收到错误。
你可以这样解决:
class Hello
class Display
# ..your Display code here..
end
end
或者像这样:
# Predefine Hello as a class name
class Hello
end
class Hello::Display
# ..your Display code here..
end
答案 1 :(得分:1)
如果在hello.rb的开头包含文件display.rb,那么当ruby解释器遇到class Hello::Display
时,它会在之前的某处定义Hello
。但此时,尚未定义类Hello
,因此您会看到错误。
答案 2 :(得分:1)
出现此错误的原因是您正在尝试在Hello
类中定义一个类,此类此时尚未定义。只需将名称分为两类:
class Hello
class Display
def initialize(name = "World")
@name = name
end
def say_hi
puts "Hello #{@name}"
end
end
end
这样你就可以一次定义两个类(稍后你可以打开Hello类)