Ruby 实例_eval不';无法访问模块中的类
我遇到了一个关于Ruby 实例_eval不';无法访问模块中的类,ruby,binding,module,scope,instance-eval,Ruby,Binding,Module,Scope,Instance Eval,我遇到了一个关于instance\u eval和模块包含的问题 请查看以下代码: module B class C def initialize puts 'This is C' end end def hello puts 'hello' end end class A include B def initialize(&block) hello C.new instance_eval(&block)
instance\u eval
和模块包含的问题
请查看以下代码:
module B
class C
def initialize
puts 'This is C'
end
end
def hello
puts 'hello'
end
end
class A
include B
def initialize(&block)
hello
C.new
instance_eval(&block)
end
end
A.new do
hello
C.new
end
当我运行这段代码时,我得到
hello
This is C
hello
-:25:in `block in ': uninitialized constant C (NameError)
from -:19:in `instance_eval'
from -:19:in `initialize'
from -:23:in `new'
from -:23:in `'
我理解这与绑定以及如何将方法和对象绑定到类有关。我无法理解的是,为什么我可以在A
中访问C
,但在我评估块时却不能。我希望它们在相同的范围内
谢谢 在下面的代码中
A.new do
hello
C.new
end
您正在尝试创建C
的对象,就好像它是在类对象的范围内定义的一样。不,不是。类C
在模块B
的范围内定义。您需要以B:C.new
的形式明确说明这一点
上面的解释是针对错误-:25:in“block in”:未初始化常量C(NameError)
我不明白的是,为什么我可以在一个小时内访问C
答案是:-
返回可在mod中访问的常量名称数组。这包括任何包含模块中的常量名称(例如在本节开头),除非继承参数设置为false
看看这个例子:
module M
X = 10
class D; Y = 10 ;end
end
class C
include M
def initialize
p self.class.constants
end
end
C.new
# >> [:X, :D]
module B
class C
def initialize
'This is C'
end
end
def hello
'hello'
end
end
class A
include B
def initialize(&block)
p self.class.constants
C.new # it will work
#instance_eval(&block)
end
end
A.new do
hello
C.new # but this will throw error.
end
# it confirms that C is accessible, within the method.
# That is the same reason you got the output "This is C"
# >> [:C]
现在应用到您的示例:
module M
X = 10
class D; Y = 10 ;end
end
class C
include M
def initialize
p self.class.constants
end
end
C.new
# >> [:X, :D]
module B
class C
def initialize
'This is C'
end
end
def hello
'hello'
end
end
class A
include B
def initialize(&block)
p self.class.constants
C.new # it will work
#instance_eval(&block)
end
end
A.new do
hello
C.new # but this will throw error.
end
# it confirms that C is accessible, within the method.
# That is the same reason you got the output "This is C"
# >> [:C]
希望能有所帮助。谢谢。这确实让我们更容易理解它到底错了什么。有没有什么方法可以不必指定完整的名称空间就可以做到这一点?